我想知道是否可以在运行时在类的对象上执行类中的方法?
首先:我有返回一个类的方法:
public static Class<?> getClassById(Long id) throws ClassNotFoundException {
if(d.id == 1L) {
return First.class;
} else if(d.id ==2L) {
return Second.class;
} else if(d.id ==3L) {
return Third.class;
} else {
throw new ClassNotFoundException();
}
}
第二:我执行它的方式:
Index.GetClassById(1)
应该返回我的类。现在我想从该类执行方法 myMethod()
。顺便说一句,(First、Second、Third) 的每个类都有这个 myMethod()
方法。
请帮忙。
最佳答案
Class
对象是代表您的类的类型的实例。这意味着 First.class.equals(new First())
将始终返回 false。
您想要的是基于您的类创建一个对象,并在该类上调用您的方法 myMethod()
,假设您的类(第一、第二、第三)有一个默认构造函数:
Class clazz = Index.getClassById(1);
First first = (First)clazz.newInstance();
first.myMethod();
这种方法的缺点是您必须显式地转换对象。
为了巧妙地中继工作,您应该定义一个定义 myMethod()
的接口(interface):
public interface MyInterface {
void myMethod();
}
public class First implements MyInterface {
...
}
public class Second implements MyInterface {
...
}
public class Third implements MyInterface {
...
}
然后您可以将上面的方法定义为:
public static Class<MyInterface> getClassById(Long id) throws ClassNotFoundException {
if(d.id == 1L) {
return First.class;
} else if(d.id ==2L) {
return Second.class;
} else if(d.id ==3L) {
return Third.class;
} else {
throw new ClassNotFoundException();
}
}
并这样调用它:
Class<MyInterface> clazz = Index.getClassById(1);
MyInterface instance = clazz.newInstance();
instance.myMethod();
关于java - 如何在 Class<?> 的对象上执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088791/