如何将 Class.getMethod 用作 getter?
How to use Class.getMethod as a getter?
我目前正在尝试将 Class.getMethod
用作 getter。
我试过用这个方法:
//This works fine
Class<?> c = Class.forName("Cat");
//This is not working
Cat cat = c.getMethod("getCat");
但是没用。
class Class 为您提供
等方法
newInstance()
调用默认构造函数
- 或
getDeclaredConstructors()
这样您就可以从 Class 个对象创建实例对象。关于如何使用反射创建实例的官方文档,请参见here。
仅 方法 getMethod()
可能的工作是:如果有一个参数 less static 具有该名称的方法猫 class,然后
Cat cat = c.getMethod("getCat").invoke(null);
可能有用。
真正的答案在这里:
- 当您是新手时,请不要假设事情可能会如何运作。阅读文档,或者一个好的教程
- 当你是新手时:不要使用反射。反思很容易让成熟的 Java 程序员发疯。真是no-go新手专区。
getMethod
returns 一个 java.lang.reflect.Method
对象。然后你需要调用它:
Cat cat = c.getMethod("getCat").invoke(null);
// Here ------------------------^
我目前正在尝试将 Class.getMethod
用作 getter。
我试过用这个方法:
//This works fine
Class<?> c = Class.forName("Cat");
//This is not working
Cat cat = c.getMethod("getCat");
但是没用。
class Class 为您提供
等方法newInstance()
调用默认构造函数- 或
getDeclaredConstructors()
这样您就可以从 Class 个对象创建实例对象。关于如何使用反射创建实例的官方文档,请参见here。
仅 方法 getMethod()
可能的工作是:如果有一个参数 less static 具有该名称的方法猫 class,然后
Cat cat = c.getMethod("getCat").invoke(null);
可能有用。
真正的答案在这里:
- 当您是新手时,请不要假设事情可能会如何运作。阅读文档,或者一个好的教程
- 当你是新手时:不要使用反射。反思很容易让成熟的 Java 程序员发疯。真是no-go新手专区。
getMethod
returns 一个 java.lang.reflect.Method
对象。然后你需要调用它:
Cat cat = c.getMethod("getCat").invoke(null);
// Here ------------------------^