反射

反射这个知识点很早就接触过了,当时是在pio做导入导出的时候,其实当时不知道那一堆代码是什么用,还伴随着很多的try catch,后在再知识库里面看到了反射的知识点,才知道有这个东西,嗨呀年少无知的我哟。这几天想着复习复习基础知识,一开始往本本上记录,记的记的就觉得写字的时候碰到写代码好烦,好想用键盘,那好,我就去写博客好了。 1.实例化class对象

Class myClass1 = null; try { myClass1 = Class.forName("com.gejiayu.learn.list.MyClass"); } catch (ClassNotFoundException e) { e.PRintStackTrace(); } Class myClass2 = new MyClass().getClass(); Class myClass3 = MyClass.class;

2.获取父类/接口

Class superClass = myClass1.getSuperclass(); Class inter[] = myClass1.getInterfaces();

3.实例化对象

MyClass myObj1; try { myObj1 = (MyClass)myClass1.newInstance(); myObj1.setAge(1); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalaccessException e) { e.printStackTrace(); }

4.获取构造方法

Constructor constructors[] = myClass1.getConstructors(); for(Constructor constructor:constructors){ Class types[] = constructor.getParameterTypes();//数据类型 }

5.获取属性

Field fields[] = myClass1.getDeclaredFields(); for(Field field:fields){ int modifier = field.getModifiers();//权限修饰符 Class type = field.getType();//数据类型 }

6.获取方法

Method methods[] = myClass1.getMethods(); for(Method method:methods){ Class type = method.getReturnType();//返回值类型 Class types[] = method.getParameterTypes();//参数类型 Class ExceptionTypes[] = method.getExceptionTypes();//异常类型 }

7.属性调用

try { field.setAccessible(true); field.set(myObj1, 3); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); }

8.方法调用

try { if("sayHello".equals(method.getName())){ method.invoke(myObj1); }else if("setAge".equals(method.getName())){ method.invoke(myObj1, 2); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }

9.method.setAccessible(true) setAccessible是启用和禁用访问安全检查的开关,并不是为true就能访问为false就不能访问。反射类中的Field,Method和Constructor继承自AccessibleObject,一般情况下,我们并不能对类的私有字段进行操作,要序列化的时候,我们又必须有能力去处理这些字段,这时候,我们就需要调用AccessibleObject上的setAccessible()方法来允许这种访问。 参考:http://blog.csdn.net/clypm/article/details/42737473

10.应用 poi操作Excel 简单工厂模式