反射是java是抽象工厂模式的利器,是IOC的基础。
本文就是分享一下使用反射调用函数方法的办法
前期准备工作(包括相关工具或所使用的原料等)IntelliJ IDEAjavareflect 详细的操作方法或具体步骤
Talk is cheap.Show me the code.
code:
package chapter3;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by MyWorld on 2016/3/16.
*/
public class RefactorInvokeMethodDemo {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
Class
Business business=businessClass.newInstance();
Method sayHelloMethod=businessClass.getDeclaredMethod("sayHello", String.class);
Object result=sayHelloMethod.invoke(business, "Baidu文库");
System.out.println(result);
}
}
class Business {
public String sayHello(String guestName) {
return "Hello ," + guestName;
}
}


执行上面的代码,看看会输出的结果是什么?
是不是期待的“Hello ,Baidu文库”
还是真是!!!
应该是嘛,完全是按api来的喽

知其然,知其所以然后。
来分析下代码:
(1)获取一个类定义:Business.class
(2)根据类定义,实例化一个实例business:businessClass.newInstance();
(3)根据类定义,使用api getDeclaredMethod获取指定的Method
(4)调用获取的Method:sayHelloMethod.invoke(business, "Baidu文库");

能不调用private的方法呢?
是可以的。
Show the code.
Code:
private String sayHello(String guestName) {
return "Hello ," + guestName;
}

执行上面的代码,看看是否能调用成功
报错了。。。
错误信息:
Exception in thread "main" java.lang.IllegalAccessException: Class chapter3.RefactorInvokeMethodDemo can not access a member of class chapter3.Business with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Method.invoke(Method.java:588)
at chapter3.RefactorInvokeMethodDemo.main(RefactorInvokeMethodDemo.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

哦。还需要设置一个地方,更改方法的private属性
Code:
Method sayHelloMethod=businessClass.getDeclaredMethod("sayHello", String.class);
sayHelloMethod.setAccessible(true);

执行最新的代码,看看是否正常了。
ok,看到熟悉的输出结果了!
O了!

- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
