1. 程式人生 > >Java反射《二》獲取構造器

Java反射《二》獲取構造器

標識 except 修飾 args anti static @class 輸出 ins

 1 package com.study.reflect;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.InvocationTargetException;
 5 
 6 /**
 7  * 通過類來反射出構造器。
 8  * @ClassName: ConstructorDemo 
 9  * @author BlueLake
10  * @date 2015年8月13日 下午5:16:07
11  */
12 public class ConstructorDemo {
13 
14     public
static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 15 16 Class c = Student.class; 17 18 //getConstructors()public修飾的構造方法 19 Constructor[] cons = c.getConstructors();
20 for(Constructor con:cons){ 21 System.out.println(con); 22 /* 23 * public com.study.reflect.Student(java.lang.String,int) 24 public com.study.reflect.Student() 25 */ 26 } 27 28 System.out.println("---------------------------------");
29 30 //getDeclaredConstructors()包括私有的方法 31 Constructor[] cons2 = c.getDeclaredConstructors(); 32 for(Constructor con:cons2){ 33 System.out.println(con); 34 /* 35 * private com.study.reflect.Student(java.lang.String) 36 public com.study.reflect.Student(java.lang.String,int) 37 public com.study.reflect.Student() 38 */ 39 } 40 System.out.println("------****************-----------"); 41 //獲取指定參數的構造器 42 Constructor one = c.getConstructor(int.class); 43 System.out.println(one);//public com.study.reflect.Student(int) 44 Class[] cls = one.getParameterTypes(); 45 for(Class cl:cls){ 46 System.out.println(cl);//int 47 System.out.println(cl.getName());//int 48 System.out.println(cl.getSimpleName());//int 49 } 50 51 Constructor two = c.getDeclaredConstructor(String.class,int.class); 52 Class[] cls2 = two.getParameterTypes(); 53 for(Class cl:cls2){ 54 //輸出類class標識和類全名。 55 System.out.println(cl);//class java.lang.String 56 //輸出參數的類全名 57 System.out.println(cl.getName());//java.lang.String 58 //輸出參數的類簡化名 59 System.out.println(cl.getSimpleName());//String 60 } 61 62 //通過參數數組來獲得構造器 63 Class[] params = new Class[2]; 64 params[0] = String.class; 65 params[1] = int.class; 66 Constructor three = c.getDeclaredConstructor(params ); 67 68 69 /** 70 * 通過獲得的構造器來創建對象 71 */ 72 Object objone = one.newInstance(18); 73 if(objone instanceof Student){ 74 Student stu = (Student)objone; 75 System.out.println(stu.getAge()); 76 } 77 78 Object objtwo = two.newInstance("項羽",27); 79 if(objtwo instanceof Student){ 80 Student stu = (Student)objtwo; 81 System.out.println(stu.getName()+"..."+stu.getAge());//項羽...27 82 } 83 84 Object objthree = three.newInstance("曹操",56); 85 if(objthree instanceof Student){ 86 Student stu = (Student)objthree; 87 System.out.println(stu.getName()+"..."+stu.getAge());//曹操...56 88 } 89 } 90 }

Java反射《二》獲取構造器