问题: [li]可以通过String类型的方法名调度方法么?[/li][li]可以获得特定的类么?比如当前类,隔壁的类,类的新实例,当前实例?[/li][li]多态的函数具有相同的名字、不同的参数类型,如何区分呢?[/li][li]如何获取指定类的参数类型等信息?[/li] 带着这些问题,我做了一些实践。总结如下: 答案:Java提供反射机制,java.lang.reflect.*,可以实现包含不限于以上功能。 下面是一些常用的通过反射获取类、调用方法的例子。关于成员、构造器的调用同理可得。想了解更多,可以查看接口文档。 package com.taobao.tuisi; public class Actions{ public void tempMethod(Long userId){ System.out.println(“我是JAVA反射测试方法,我被invoke了” + userId); } public void temp() throws Exception{ //1.获得class //获得类的当前实例 Actions a = this; System.out.println(a); //输出 com.taobao.tuisi.Actions$$EnhancerByCGLIB$$dff89711@c2ccac //获得指定类的新实例 Actions b = Actions.class.newInstance(); System.out.println(b); //输出 com.taobao.tuisi.Actions@1e4fede // //通过类型获得类 Class boolType = Boolean.class; System.out.println(boolType); //输出 class java.lang.Boolean // //通过变量获得类 String stringExample = “”; Class stringType = stringExample.getClass(); System.out.println(stringType); //输出class java.lang.String // //由名字获得类 Class<?> c = Class.forName(“com.taobao.tuisi.Actions”); System.out.println(c); //输出 class com.taobao.tuisi.Actions // //2.关于method //由函数名和参数类型得到函数 Long userId = 9999l; Method method = Actions.class.getDeclaredMethod(“tempMethod”, userId.getClass()); System.out.println(method); //输出 public void com.taobao.tuisi.Actions.tempMethod(java.lang.Long) // //通过类、参数值调用指定函数 Actions actions = new Actions(); Long args[] = new Long [1]; args[0] = userId; method.invoke(actions, args); //输出 我是JAVA反射测试方法,我被invoke了9999 } } Java是一门最有前景的面向对象语言,学习java是许多人获得高薪的方法!现在学习java最好就是参加java培训,广州java培训机构有很多,选择一个合适的java培训机构对于我们的就业是很重要的。因此大家一定要擦亮眼睛。选择合适的java培训机构
QQ 744437114
|