无风无影

   ::  :: 新随笔  ::  ::  :: 管理

java反射

  1 package com.sfbest.financial.basedata.utils;
  2 
  3 import java.lang.reflect.Constructor;
  4 import java.lang.reflect.Field;
  5 import java.lang.reflect.InvocationTargetException;
  6 import java.lang.reflect.Method;
  7 import java.lang.reflect.Modifier;
  8 
  9 public class Main {  
 10     /** 
 11      * 为了看清楚Java反射部分代码,所有异常我都最后抛出来给虚拟机处理! 
 12      * @param args 
 13      * @throws ClassNotFoundException 
 14      * @throws InstantiationException 
 15      * @throws IllegalAccessException 
 16      * @throws InvocationTargetException  
 17      * @throws IllegalArgumentException  
 18      * @throws NoSuchFieldException  
 19      * @throws SecurityException  
 20      * @throws NoSuchMethodException  
 21      */  
 22     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchFieldException, NoSuchMethodException {  
 23         // TODO Auto-generated method stub  
 24           
 25         //Demo1.  通过Java反射机制得到类的包名和类名  
 26           /*  Demo1();  
 27         System.out.println("===============================================");  
 28           
 29       //Demo2.  验证所有的类都是Class类的实例对象  
 30         Demo2();  
 31         System.out.println("==============================================="); 
 32           
 33           //Demo3.  通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在],无参构造  
 34         Demo3();  
 35         System.out.println("===============================================");  
 36           
 37         //Demo4:  通过Java反射机制得到一个类的构造函数,并实现构造带参实例对象  
 38         /*Demo4();  
 39         System.out.println("===============================================");  
 40           
 41         //Demo5:  通过Java反射机制操作成员变量, set 和 get  
 42         Demo5();  
 43         System.out.println("===============================================");  
 44           
 45         //Demo6: 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等  
 46         Demo6();  
 47         System.out.println("===============================================");  
 48           
 49         //Demo7: 通过Java反射机制调用类中方法  
 50         Demo7();  
 51         System.out.println("===============================================");   */
 52           
 53         //Demo8: 通过Java反射机制获得类加载器  
 54         Demo8();  
 55         System.out.println("===============================================");  
 56           
 57     }  
 58       
 59     /** 
 60      * Demo1: 通过Java反射机制得到类的包名和类名 
 61      */  
 62     public static void Demo1()  
 63     {  
 64         Person person = new Person();  
 65         System.out.println("Demo1: 包名: " + person.getClass().getPackage().getName() + ","   
 66                 + "完整类名: " + person.getClass().getName());  
 67     }  
 68       
 69     /** 
 70      * Demo2: 验证所有的类都是Class类的实例对象 
 71      * @throws ClassNotFoundException  
 72      */  
 73     public static void Demo2() throws ClassNotFoundException  
 74     {  
 75         //定义两个类型都未知的Class , 设置初值为null, 看看如何给它们赋值成Person类  
 76         Class<?> class1 = null;  
 77         Class<?> class2 = null;  
 78           
 79         //写法1, 可能抛出 ClassNotFoundException [多用这个写法]  
 80         class1 = Class.forName("cn.lee.demo.Person");  
 81         System.out.println("Demo2:(写法1) 包名: " + class1.getPackage().getName() + ","   
 82                 + "完整类名: " + class1.getName());  
 83           
 84         //写法2  
 85         class2 = Person.class;  
 86         System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName() + ","   
 87                 + "完整类名: " + class2.getName());  
 88     }  
 89       
 90     /** 
 91      * Demo3: 通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在] 
 92      * @throws ClassNotFoundException  
 93      * @throws IllegalAccessException  
 94      * @throws InstantiationException  
 95      */  
 96     public static void Demo3() throws ClassNotFoundException, InstantiationException, IllegalAccessException  
 97     {  
 98         Class<?> class1 = null;  
 99         class1 = Class.forName("cn.lee.demo.Person");  
100         //由于这里不能带参数,所以你要实例化的这个类Person,一定要有无参构造函数哈~  
101         Person person = (Person) class1.newInstance();  
102         person.setAge(20);  
103         person.setName("LeeFeng");  
104         System.out.println("Demo3: " + person.getName() + " : " + person.getAge());  
105     }  
106       
107     /** 
108      * Demo4: 通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象 
109      * @throws ClassNotFoundException  
110      * @throws InvocationTargetException  
111      * @throws IllegalAccessException  
112      * @throws InstantiationException  
113      * @throws IllegalArgumentException  
114      */  
115     public static void Demo4() throws ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException  
116     {  
117         Class<?> class1 = null;  
118         Person person1 = null;  
119         Person person2 = null;  
120           
121         class1 = Class.forName("cn.lee.demo.Person");  
122         //得到一系列构造函数集合  
123         Constructor<?>[] constructors = class1.getConstructors();  
124           
125         person1 = (Person) constructors[0].newInstance();  
126         person1.setAge(30);  
127         person1.setName("leeFeng");  
128           
129         person2 = (Person) constructors[1].newInstance(20,"leeFeng");  
130           
131         System.out.println("Demo4: " + person1.getName() + " : " + person1.getAge()  
132                 + "  ,   " + person2.getName() + " : " + person2.getAge()  
133                 );  
134           
135     }  
136       
137     /** 
138      * Demo5: 通过Java反射机制操作成员变量, set 和 get 
139      *  
140      * @throws IllegalAccessException  
141      * @throws IllegalArgumentException  
142      * @throws NoSuchFieldException  
143      * @throws SecurityException  
144      * @throws InstantiationException  
145      * @throws ClassNotFoundException  
146      */  
147     public static void Demo5() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException, InstantiationException, ClassNotFoundException  
148     {  
149         Class<?> class1 = Class.forName("cn.lee.demo.Person");  
150         Object obj = class1.newInstance();  
151         Field personNameField = class1.getDeclaredField("name");  
152         personNameField.setAccessible(true);  
153         personNameField.set(obj, "胖虎先森");  
154           
155           
156         System.out.println("Demo5: 修改属性之后得到属性变量的值:" + personNameField.get(obj));  
157           
158     }  
159       
160   
161     /** 
162      * Demo6: 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等 
163      * @throws ClassNotFoundException  
164      */  
165     public static void Demo6() throws ClassNotFoundException  
166     {  
167         Class<?> class1 = null;  
168         class1 = Class.forName("cn.lee.demo.SuperMan");  
169           
170         //取得父类名称  
171         Class<?>  superClass = class1.getSuperclass();  
172         System.out.println("Demo6:  SuperMan类的父类名: " + superClass.getName());  
173           
174         System.out.println("===============================================");  
175           
176           
177         Field[] fields = class1.getDeclaredFields();  
178         for (int i = 0; i < fields.length; i++) {  
179             System.out.println("类中的成员: " + fields[i]);  
180         }  
181         System.out.println("===============================================");  
182           
183           
184         //取得类方法  
185         Method[] methods = class1.getDeclaredMethods();  
186         for (int i = 0; i < methods.length; i++) {  
187             System.out.println("Demo6,取得SuperMan类的方法:");  
188             System.out.println("函数名:" + methods[i].getName());  
189             System.out.println("函数返回类型:" + methods[i].getReturnType());  
190             System.out.println("函数访问修饰符:" + Modifier.toString(methods[i].getModifiers()));  
191             System.out.println("函数代码写法: " + methods[i]);  
192         }  
193           
194         System.out.println("===============================================");  
195           
196         //取得类实现的接口,因为接口类也属于Class,所以得到接口中的方法也是一样的方法得到哈  
197         Class<?> interfaces[] = class1.getInterfaces();  
198         for (int i = 0; i < interfaces.length; i++) {  
199             System.out.println("实现的接口类名: " + interfaces[i].getName() );  
200         }  
201           
202     }  
203       
204     /** 
205      * Demo7: 通过Java反射机制调用类方法 
206      * @throws ClassNotFoundException  
207      * @throws NoSuchMethodException  
208      * @throws SecurityException  
209      * @throws InvocationTargetException  
210      * @throws IllegalAccessException  
211      * @throws IllegalArgumentException  
212      * @throws InstantiationException  
213      */  
214     public static void Demo7() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException  
215     {  
216         Class<?> class1 = null;  
217         class1 = Class.forName("cn.lee.demo.SuperMan");  
218           
219         System.out.println("Demo7: \n调用无参方法fly():");  
220         Method method = class1.getMethod("fly");  
221         method.invoke(class1.newInstance());  
222           
223         System.out.println("调用有参方法walk(int m):");  
224         method = class1.getMethod("walk",int.class);  
225         method.invoke(class1.newInstance(),100);  
226     }  
227       
228     /** 
229      * Demo8: 通过Java反射机制得到类加载器信息 
230      *  
231      * 在java中有三种类类加载器。[这段资料网上截取] 
232  
233         1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。 
234  
235         2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类 
236  
237         3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。 
238      *  
239      * @throws ClassNotFoundException  
240      */  
241     public static void Demo8() throws ClassNotFoundException  
242     {  
243         Class<?> class1 = null;  
244         class1 =SuperMan.class;  
245         String nameString = class1.getClassLoader().getClass().getName();  
246           
247         System.out.println("Demo8: 类加载器类名: " + nameString);  
248     }  
249       
250       
251       
252 }  
253 /** 
254  *  
255  * @author xiaoyaomeng 
256  * 
257  */  
258 class  Person{  
259     private int age;  
260     private String name;  
261     public Person(){  
262           
263     }  
264     public Person(int age, String name){  
265         this.age = age;  
266         this.name = name;  
267     }  
268   
269     public int getAge() {  
270         return age;  
271     }  
272     public void setAge(int age) {  
273         this.age = age;  
274     }  
275     public String getName() {  
276         return name;  
277     }  
278     public void setName(String name) {  
279         this.name = name;  
280     }  
281 }  
282   
283 class SuperMan extends Person implements ActionInterface  
284 {  
285     private boolean BlueBriefs;  
286       
287     public void fly()  
288     {  
289         System.out.println("超人会飞耶~~");  
290     }  
291       
292     public boolean isBlueBriefs() {  
293         return BlueBriefs;  
294     }  
295     public void setBlueBriefs(boolean blueBriefs) {  
296         BlueBriefs = blueBriefs;  
297     }  
298   
299     @Override  
300     public void walk(int m) {  
301         // TODO Auto-generated method stub  
302         System.out.println("超人会走耶~~走了" + m + "米就走不动了!");  
303     }  
304 }  
305 interface ActionInterface{  
306     public void walk(int m);  
307 }  
View Code

 

 

比如在代码中声明了一个域是List<String>类型的,虽然在运行时刻其类型会变成原始类型List,但是仍然可以通过反射来获取到所用的实际的类型参数。

 1 Field field = Pair.class.getDeclaredField("myList"); //myList的类型是List 
 2 Type type = field.getGenericType(); 
 3 if (type instanceof ParameterizedType) {     
 4     ParameterizedType paramType = (ParameterizedType) type;     
 5     Type[] actualTypes = paramType.getActualTypeArguments();     
 6     for (Type aType : actualTypes) {         
 7         if (aType instanceof Class) {         
 8             Class clz = (Class) aType;             
 9             System.out.println(clz.getName()); //输出java.lang.String         
10         }     
11     } 
12 } 
View Code

 

posted on 2018-06-06 17:53  NWNS-无风无影  阅读(148)  评论(0)    收藏  举报