我想定义一个函数来创建共享相同基类的不同类型对象。我想传入对象类型并让函数创建对象,然后修改其属性。问题是创建所有这些对象的主类没有该对象的属性,因此代码无法编译。
示例:
public void new_generic_report(Class report_class, String report_name) {
Report new_report = this.reportManager.createReport(report_class);
new_report.set_name(report_name);
}
调用 new_generic_report(GreenReport.class, "green_report");
失败,因为 new_report 属于 Report 类而不是 GreenReport 类,因此它没有 .set_name 方法。
我知道我可以在主 Report 类中实现 .set_name 方法(以及其他常用方法),但我正在编写代码来与我无法修改的 API 进行交互。
最佳答案
如果您确定 createReport 返回正确类的实例,您可以进行强制转换:
((SpecialClass)new_report).set_name(report_name);
另一种方法是使用反射:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
static class Base {};
static class Child extends Base {
public void setName(final String name) {
System.out.println("setName("+name+")");
}
}
public static void main(String[] args) {
new Test().new_generic_report(Child.class, "Testname");
}
public void new_generic_report(final Class clazz, final String name) {
Base base = createBase(clazz);
try {
Method m = clazz.getMethod("setName", String.class);
m.invoke(base, name);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private Base createBase(Class report_class) {
return new Child();
}
}
当然,只有当返回的实例实现该方法时,这才有效。
关于java - 根据类参数在函数中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461676/