我有两个java类(Child1.java and Child2.java),它是从一个公共类(Parent.java)扩展而来的。我有另一个公共类(Common.java),它可以从两个子类中调用。我从Thread.currentThread().getStackTrace()获取调用者类名,并通过Java Reflection创建类实例。然后,我将从该类创建一个新的实例对象。因此,该方法的返回类型为Object
尽管我现在正在返回一个对象,但我需要以这样一种方式编写commonMethod():被调用的类的新实例应该是动态返回的。
public class Child1 extends Parent {
public void method1()
{
new Common().commonMethod();
}
}
public class Child2 extends Parent {
public void method2()
{
new Common().commonMethod();
}
}
public Object commonMethod() throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
Class clazz = Class.forName(className);
return clazz.newInstance();
}任何帮助都将不胜感激
发布于 2019-01-22 14:26:22
试试这个:
public Parent commonMethod() {
// blah blah..
} public class Child1 extends Parent {
public void method1()
{
new Common() {
@Override
public Child1 commonMethod() {
return new Child1();
}
}.commonMethod();
}
}
public class Child2 extends Parent {
public void method2()
{
new Common() {
@Override
public Child2 commonMethod() {
return new Child2();
}
}.commonMethod();
}
}你的结构不好。
但我认为这是有原因的。祝好运。
发布于 2019-01-22 14:29:35
这是你想要的吗?
public <T extends Object>T commonMethod() throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
Class clazz = Class.forName(className);
return (T) clazz.newInstance();
}https://stackoverflow.com/questions/54302138
复制相似问题