反射:運(yùn)行時(shí)類(lèi)信息
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、動(dòng)態(tài)代理
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");