我有代码:
1 abstract class A {
2 public abstract <T> T getId();
3 }
4 class B extend A {
5 public Long getId() {
6 return Long.valueOf(1);
7 }
8 }
9 public class Main {
10 public static void main(String [] args) {
11 FastClass fast = FastClass.create(B.class);
12 FastMethod fastMethod = fast.getMethod("getId", null);
13 try {
14 final B b = new B();
15 Long value = (Long) fastMethod.invoke(b, null);
16 } catch (Exception e) {//
17 e.printStackTrace();
18 }
19 }
20 }
并在第12行抛出 IllegalArgumentException:找不到方法public java.lang.Long B.getId()。
如何获取实例FastMethod类并执行FastMethod.invoke()?
答案 0 :(得分:0)
我必须为类 A 获取实例 FastClass 并从中获取实例 FastMethod ,但调用实例 FastMethod 参数实例类 B 。
此代码可以正常工作:
1 abstract class A {
2 public abstract <T> T getId();
3 }
4 class B extend A {
5 public Long getId() {
6 return Long.valueOf(1);
7 }
8 }
9 public class Main {
10 public static void main(String [] args) {
11 FastClass fast = FastClass.create(A.class); // changed, was FastClass.create(B.class)
12 FastMethod fastMethod = fast.getMethod("getId", null);
13 try {
14 final B b = new B();
15 Long value = (Long) fastMethod.invoke(b, null);
16 } catch (Exception e) {
17 e.printStackTrace();
18 }
19 }
20 }