JAVA 反射

来源:互联网 发布:电脑截图软件下载 编辑:程序博客网 时间:2024/06/09 23:39

Java 反射机制

本文主要是学习反射的一些核心知识点

反射概念

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性。

反射支持

Class类库与java.lang.reflect类库一起支持反射,包含了Field、Method以及Constructor类。
Class.forName()在编译器不可知。

反射作用

1.获取类

// 方式1Class myClass = Class.forName("MyClass");// 方式2Class myClass = MyClass.class;// 方式3Class myClass = (new MyClass()).getClass();

2.创建对象

Class myClass = Class.forName("MyClass");Myclass my = (MyClass)myClass.newInstance();

3.获取属性

Class myClass = Class.forName("MyClass");// 所有属性Field[] fields = myClass.getDeclaredFields();Fleld field = myClass.getDeclaredField("param");

剩余获取方法、构造函数、返回值等,就不列举了。
反射可以获取一切你想得到的类中的元素。

反射的应用

动态代理

  • 实现InvocationHandler方法
  • 覆盖invoke方法
  • invoke方法通过method.invoke方法返回对象
interface ProxyInterface {    void show();}class ProxyImpl implements  ProxyInterface {    public void show() {        System.out.println("proxyImpl show");    }}class myProxy implements InvocationHandler {    private Object proxyImpl = null;    public myProxy (Object proxy) {        this.proxyImpl = proxy;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("proxy show before");        Object result =  method.invoke(proxyImpl, args);        System.out.println("proxy show after");        return result;    }}public class Main {    public static void main(String[] args) {        ProxyInterface user = new ProxyImpl();        InvocationHandler in = new myProxy(user);        ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(user.getClass().getClassLoader(), user.getClass().getInterfaces(), in);        proxy.show();    }}

应用场景

Hibernate
- 配置注入
-JDBC配置

Spring
- 初始化Bean
- 依赖注入

反射原理

Class.forName实际上调用了类加载器(双亲委派加载),首先从Cache中查找类,如果没有,则用类加载器加载。

优缺点

优点

  • 增加程序灵活性
  • 与Java动态编译结合,功能性强大

缺点

  • 性能低下
  • 相对不安全
  • 破坏了封装性
0 0