2018-11-19 反射

反射:运行时类信息

Person person = new Person("luoxn28", 23);

    Class clazz = person.getClass();

    Field[] fields = clazz.getDeclaredFields();

    for (Field field : fields) {

        String key = field.getName();

        PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);

        Method method = descriptor.getReadMethod();

        Object value = method.invoke(person);

        System.out.println(key + ":" + value);

    }

4、动态代理

public interface Interface {

    void doSomething();

    void somethingElse(String arg);

}

public class RealObject implements Interface {

    public void doSomething() {

      // System.out.println("doSomething.");

    }

    public void somethingElse(String arg) {

      // System.out.println("somethingElse " + arg);

    }

}

public class DynamicProxyHandler implements InvocationHandler {

    private Object proxyed;


    public DynamicProxyHandler(Object proxyed) {

        this.proxyed = proxyed;

    }


    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        System.out.println("代理工作了.");

        return method.invoke(proxyed, args);

    }

}

RealObject real = new RealObject();

        Interface proxy = (Interface) Proxy.newProxyInstance(

                Interface.class.getClassLoader(), new Class[] {Interface.class},

                new DynamicProxyHandler(real));


        proxy.doSomething();

        proxy.somethingElse("luoxn28");

你可能感兴趣的:(2018-11-19 反射)