[英]How to use Class.getMethod as a getter?
我目前正在尝试使用Class.getMethod
作为吸气剂。
我尝试使用这种方法:
//This works fine
Class<?> c = Class.forName("Cat");
//This is not working
Cat cat = c.getMethod("getCat");
但它不起作用。
类 Class 为您提供方法,例如
newInstance()
调用默认构造函数getDeclaredConstructors()
这样你就可以从 Class 对象创建实例对象。 有关如何使用反射创建实例的官方文档,请参见此处。
getMethod()
可能起作用的唯一方法是:如果 Cat 类上有一个具有该名称的无参数静态方法,则
Cat cat = c.getMethod("getCat").invoke(null);
可能工作。
真正的答案在这里:
getMethod
返回一个java.lang.reflect.Method
对象。 然后你需要调用它:
Cat cat = c.getMethod("getCat").invoke(null);
// Here ------------------------^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.