Java反射机制

时间:2020-07-01 09:46:44   收藏:0   阅读:41

Java反射机制

程序可以访问,检测和修改本身状态或行为的能力。

类的组成:

发射机制的功能:

相关API

通过一个对象获得完整的包名和类名

动态绑定

interface Animal{
    void eat();
    void walk();
}

class Dog implements Animal{
    @Override
    public void eat() {
        System.out.println("Dog is eating!");
    }
    @Override
    public void walk() {
        System.out.println("Dog is walking!");
    }
}

class Cat implements Animal{
    @Override
    public void eat() {
        System.out.println("Cat is eating!");
    }
    @Override
    public void walk() {
        System.out.println("Cat is walking!");
    }
}
// 代理类
// 1. 方式一
class AnimalProxy implements InvocationHandler{
    private Object target;
    public AnimalProxy(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Invoke AnimalProxy");
        Object res = method.invoke(target, args);
        return res;
    }
}

// 2. 方式二
class newAnimalProxy implements InvocationHandler{
    private Object target;
    public Object bind(Object target){
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterface(),this);
    }
}
// 1. 方式一代理测试
@Test
public void test(){
    // 代理Dog类
    Animal dog = new Dog();
    Animal proxy = (Animal)Proxy.newProxyInstance(dog.getClass().getClassLoader(),dog.getClass().getInterface(),new AnimalProxy(dog));
    proxy.eat();
    proxy.walk();

    // 代理Cat类
    Animal cat = new Cat();
    Animal proxy = (Animal)Proxy.newProxyInstance(cat.getClass().getClassLoader(),cat.getClass().getInterface(),new AnimalProxy(cat));
    proxy.eat();
    proxy.walk();
}

// 2. 方式二代理测试
@Test
public void newTest(){
    newAnimalProxy proxy = new newAnimalProxy(); // 创建代理类
    Animal getDog = (Animal)proxy.bind(new Dog()); // 绑定需要代理的对象(使用接口类)
    getDog.eat(); // 调用对象方法
    getDog.walk();
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!