Java 能否多重反射

Java反射机制能否支持多重反射。

如,动态invoke一个方法里还有一个invoke

求大牛详解!

若不能,有没有其它偏方可以实现这种效果?


HUWWW
浏览 487回答 3
3回答

牧羊人nacy

我试验了一下,这是没有任何问题的。代码:// Main.javaclass Main {&nbsp; &nbsp; public void static main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class<?> c = Class.forName(args[0]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object o = c.newInstance();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Method m = c.getMethod("doSth");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.invoke(o);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;}// A.javaclass A {&nbsp; &nbsp; public void doSth() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Inside A.doSth: using reflection to call B");&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class<?> c = Class.forName("B");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object o = c.newInstance();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Method m = c.getMethod("doOther");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.invoke(o);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}// B.javaclass B {&nbsp; &nbsp; public void doOther() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Inside B");&nbsp; &nbsp; }}

www说

只要是签名合法的方法的字节码都是可以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.

慕哥6287543

当然可以。只要你能看懂其间多次反射的逻辑。。。。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java