JAVA 反射

Java 反射机制

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

反射概念

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

反射支持

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

反射作用

1.获取类

// 方式1
Class myClass = Class.forName("MyClass");
// 方式2
Class myClass = MyClass.class;
// 方式3
Class 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动态编译结合,功能性强大
缺点
  • 性能低下
  • 相对不安全
  • 破坏了封装性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值