3 回答

TA貢獻1862條經驗 獲得超7個贊
我試驗了一下,這是沒有任何問題的。
代碼:
// Main.java
class Main {
public void static main(String[] args) {
try {
Class<?> c = Class.forName(args[0]);
Object o = c.newInstance();
Method m = c.getMethod("doSth");
m.setAccessible(true);
m.invoke(o);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// A.java
class A {
public void doSth() {
System.out.println("Inside A.doSth: using reflection to call B");
try {
Class<?> c = Class.forName("B");
Object o = c.newInstance();
Method m = c.getMethod("doOther");
m.setAccessible(true);
m.invoke(o);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// B.java
class B {
public void doOther() {
System.out.println("Inside B");
}
}

TA貢獻1775條經驗 獲得超8個贊
只要是簽名合法的方法的字節碼都是可以invoke的,和方法中的字節碼具體做什么沒有關系也沒有限制。
但是你要想好為什么這么做。
Greenspun's tenth rule of programming:
Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
添加回答
舉報