写一段java代码 传入一种class类型,返回对应对象类型的对象
时间: 2024-04-23 13:08:18 浏览: 146
public static <T> T getObject(Class<T> clazz) throws Exception {
return clazz.getDeclaredConstructor().newInstance();
}
// 示例使用:
MyObject myObject = getObject(MyObject.class);
相关问题
写一段java代码 传入一种class类型,并且封装一些属性后,返回对应对象类型的对象
```
public class MyClass {
private String name;
private int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ObjectCreator {
public static <T> T createObject(Class<T> clazz, String name, int age) throws Exception {
T obj = clazz.getDeclaredConstructor(String.class, int.class).newInstance(name, age);
return obj;
}
}
// Example usage:
MyClass myObj = ObjectCreator.createObject(MyClass.class, "John", 30);
```
阅读全文