初学反射

来源:互联网 发布:传感器网络 sci期刊 编辑:程序博客网 时间:2024/06/01 20:39

反射:获得字节码文件的三种方法:

1  Class c1 = Class.forName("com.aowin.homework_reflect.Child");2  Class c2=new Child().getClass();3  Class c3 = Child.class;


初始化构造函数:
1  Child child=(Child)c2.newInstance();2  Object obj2=c2.newInstance();3  Object obj=c2.getConstructor(String.class).newInstance("突破天际");4  获得私有构造函数    Constructor con4=c2.getDeclaredConstructor(String.class,int.class);    con4.setAccessible(true);    Object obj=con4.newInstance("llo",10);
直接转换成Child,优点是调用方法和属性方便,和普通实例化Child对象一样;缺点:得不到私有化的属性和方法

获得方法:

1  child.eatApple(10);2  c2.getMethod("eatApple", int.class).invoke(obj2, 10);3  c.getMethod("print1").invoke(null);//调用静态方法4  调用私有方法    Method method=c2.getDeclaredMethod("eatApple", int.class,String.class);    method.setAccessible(true);    method.invoke(obj2, 5,"I am full");


获得属性:

1  int id=child.id;2  Object id=c2.getField("id").get(obj2);3  获得私有属性    Field name=c2.getDeclaredField("name");    name.setAccessible(true);    Object namee=name.get(obj2);


用于遍历:

Constructor[] con=c2.getConstructors();Constructor[] con2=c2.getDeclaredConstructors();Method[] methods=c2.getMethods();//获得包括父类的所以public方法Method[] methods2=c2.getDeclaredMethods();Field[] fields=c2.getFields();Field[] fieldss=c2.getDeclaredFields();

ArrayList数组反射赋值:

Class c=ArrayList.class;Object con=c.newInstance();Method method=c.getMethod("add",Object.class);method.invoke(con, "hello");System.out.println(con);

 动态代理接口:Proxy代理人类和Interface接口,仅限代理接口, 代理抽象类用cglib

1 自己写一个代理类,实现接口:InvocationHandler

<pre name="code" class="java">public class MyInvocationHandler implements InvocationHandler {private Object target;public MyInvocationHandler(Object target) {this.target=target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] arg2)throws Throwable {System.out.println("权限验证");Object objreturn=method.invoke(target, arg2);System.out.println("日志记录");return objreturn;}}

调用代理人类(UserDao为接口类):

<pre name="code" class="java">Object ud=UserDao.class.newInstance();
MyInvocationHandler myin = new MyInvocationHandler(ud);
UserDao proxy = (UserDao) Proxy.newProxyInstance(ud.getClass().getClassLoader(), ud.getClass().getInterfaces(), myin);
proxy.add();//UserDao里面的方法










0 0
原创粉丝点击