Java反射《二》获取构造器
Posted 溪山晴雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java反射《二》获取构造器相关的知识,希望对你有一定的参考价值。
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反射《二》获取构造器的主要内容,如果未能解决你的问题,请参考以下文章