我正在尝试学习Method Reflect,以便我可以在我的Java应用程序中应用。
我创建了两个POJO类。
愿望.java
public class Wishes {
private String greeting;
public String getGreeting() {
this.greeting="Good Afternoon!";
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
天.java
public class Day {
private Wishes wishes;
public Wishes getWishes() {
return wishes;
}
public void setWishes(Wishes wishes) {
this.wishes = wishes;
}
}
这就是我在主要方法中所做的。演示应用.java
public class DemoApp {
public static void main(String[] args) {
try {
Class cls=Wishes.class;
Method method1=cls.getDeclaredMethod("getGreeting");
String result1=(String) method1.invoke(cls.newInstance());
System.out.println(result1);
Class clazz=Day.class;
Method method=clazz.getDeclaredMethod("getWishes().getGreeting");
String result=(String) method.invoke(clazz.newInstance());
System.out.println(result);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
我运行应用程序。对于第一个,我得到了准确的输出,因为它很简单。但对于第二个,我得到了例外。下面是控制台输出和堆栈跟踪。
Good Afternoon!
java.lang.NoSuchMethodException: com.myapp.demo.Day.getWishes().getGreeting()
at java.lang.Class.getDeclaredMethod(Class.java:2004)
at com.myapp.demo.DemoApp.main(DemoApp.java:17)
如何从getWishes
调用getGreeting
方法Day
方法与方法反射一起使用类?可能吗?否则,使用方法反射做到这一点的最佳方法是什么?
在我的应用程序中,我获得的方法名称来自一个 XML 文件。因此,它可能包含单个方法或方法调用序列,如上所示。
首先在日间课程中,您应该发起愿望
private Wishes wishes = new Wishes();
其次,您需要这样做:
Method method=clazz.getDeclaredMethod("getWishes");
Object result= method.invoke(clazz.newInstance());
Method method2=result.getClass().getDeclaredMethod("getGreeting");
String result2=(String) method2.invoke(cls.newInstance());
System.out.println(result2);
方法Class#getDeclaredMethod
采用方法的名称及其参数的类型。您正在将字符串getWishes().getGreeting
不是有效的方法名称。你想使用
Method method = clazz.getDeclaredMethod("getWishes");
为了从Day
实例中获取Wishes
实例,应该做什么。对于收到的实例,您可以反射方式调用 getGreeting
方法。您建议的方法链接不适用于反射。但是,有一些库简化了反射API,例如链式属性的Bean访问。但是,出于学习目的,您需要手动链接反射调用。
反射调用不堆叠。因此,您调用方法getGreeting
的方式不起作用。
您可以尝试以下方式:
Class cls=Wishes.class;
Method method1=cls.getDeclaredMethod("getGreeting");
String result1=(String) method1.invoke(cls.newInstance());
System.out.println(result1);
Class clazz=Day.class;
Object ob = clazz.newInstance();
Method method2=clazz.getDeclaredMethod("setWishes", cls);
method2.invoke(ob, cls.newInstance());
Method method=clazz.getDeclaredMethod("getWishes");
Object day =(Object) method.invoke(ob);
System.out.println(((Wishes)day).getGreeting());
注意:可以进一步重构此代码段以满足您的要求
在Day类上没有这样的方法"getWishes().getGreeting"。 你要做的是。
- 调用 "Day.getWishes() 并获取输出
- 在上述输出对象之上调用 getGreeting
在序列上,您必须一个接一个地执行。
顺便说一下,我认为值得看看JXPath库作为替代方案。您可以给出一个复杂的对象并进行 XPath 搜索。
反射调用不会堆叠 - 在课堂日中没有名称为"getWishes().getGreeting()"的方法。
您需要首先调用"Day.getWishes()",然后在返回的对象上调用"getGreeting()"。