600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Java 反射调用方法实例 动态动用方法实例

Java 反射调用方法实例 动态动用方法实例

时间:2024-04-21 17:31:34

相关推荐

Java 反射调用方法实例 动态动用方法实例

包结构

Hello.java

package test;public class Hello {public double add (double score1, double score2){return score1 + score2;}public void print(){System.out.println("OK");}public static double mul(double score1, double score2){return score1 * score2;}}

CalculatorTest.java

package test;import java.lang.reflect.Method;class Calculator{public Calculator(){//这个构造器仅有一个参数:nameSystem.out.println("Calculator 构造函数");}public String eDIo(String str){String str_temp = "";str_temp = str.replace("World", "Hello");return str_temp;}}public class CalculatorTest {public static void main(String[] args) throws Exception {Calculator cal = new Calculator();String str_class_name = cal.eDIo("test.World");//方法一:通过类的.class属性获取//Class<Hello> clz = Hello.class;//方法二:通过类的完整路径获取,这个方法由于不能确定传入的路径是否正确,这个方法会抛ClassNotFoundExceptionClass clz = Class.forName(str_class_name);//方法三:new一个实例,然后通过实例的getClass()方法获取//Hellos=newHello();//Class<Hello>clz=s.getClass();//1.获取类中带有方法签名的mul方法,getMethod第一个参数为方法名,第二个参数为mul的参数类型数组Method method = clz.getMethod("mul", new Class[]{double.class, double.class});//invoke方法的第一个参数是被调用的对象,这里是静态方法故为null,第二个参数为给将被调用的方法传入的参数Object result = method.invoke(null, new Object[]{2.0, 2.5});//如果方法mul是私有的private方法,按照上面的方法去调用则会产生异常NoSuchMethodException,这时必须改变其访问属性//method.setAccessible(true);//私有的方法通过发射可以修改其访问权限System.out.println(result);//结果为5.0//2.获取类中的非静态方法Method method_2 = clz.getMethod("add", new Class[]{double.class, double.class});//这是实例方法必须在一个对象上执行Object result_2 = method_2.invoke(new Hello(), new Object[]{2.0, 2.5});System.out.println(result_2);//4.5//3.获取没有方法签名的方法printMethod method_3 = clz.getMethod("print", new Class[]{});Object result_3 = method_3.invoke(new Hello(), null);//result_3为null,该方法不返回结果}}

运行结果

Calculator 构造函数

5.0

4.5

OK

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。