Java反射总结
java中有三种类类加载器。
1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。
2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类
3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。
ClassLoader loader = Thread.currentThread().getContextClassLoader();Class.getClassLoader() ;
实例化Class类对象的三种方式:
Class.forName("Reflect.Demo");new Demo().getClass();Demo.class;Class<?> demo=Class.forName("Reflect.Person");Constructor<?> cons[]=demo.getConstructors();Object object = cons[0].newInstance(args);Class<?> intes[]=demo.getInterfaces();
Class<?> superClass=demo.getSuperclass();
demo = Class.forName("Reflect.Demo");Method method=demo.getMethod("toString");method.invoke(demo.newInstance());Method[] methods = demo.getDeclaredMethods(); Field field = demo.getDeclaredField("sex");field.setAccessible(true);field.set(obj, "男");Field[] fields = Demo.class.getDeclaredFields(); //类中任何可见性的属性不包括基类fields = Demo.class.getFields(); //只能获得public属性包括基类的 Class string = Class.forName("java.lang.String"); Object object= Array.newInstance(string, 10); Array.set(object, 5, "this is a test"); String s = (String) Array.get(arr, 5); public class MyHandler implements InvocationHandler { private Object target; public Object bind(Object target) { this.target = target; return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("事物开始"); Object result = method.invoke(target, args); System.out.println("事物结束"); return result; } } public class MyCglib implements MethodInterceptor { private Object target; public Object getInstance(Object target) { this.target = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); // 回调方法 enhancer.setCallback(this); // 创建代理对象 return enhancer.create(); } @Override // 回调方法 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("事物开始"); proxy.invokeSuper(obj, args); System.out.println("事物结束"); return null; } }