package com.niu.demo.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Reflect{ public static void main(String[] args){ Person p = Person.getPerson(); //getClass对象所在的类 Class cp = p.getClass(); //getName获取类名 String className = cp.getName(); System.out.println(className); //基础类型也有对应的Class Class t1 = double.class; Class t2 = int[].class; System.out.println("基础类型的Class: "+t1.getName()+" "+t2.getName()); try{ //第一种 Class cp_A = Class.forName(className); Person p_A = new Person("Zhang",20); //第二种 Class cp_B = p_A.getClass(); //第三种 Class cp_C = Person.class; //不管通过某种方式获取类的Class实例,都将是同一个 //ture System.out.println("同一个类的多个实例返回的Class相同:"+(cp==cp_A&&cp_A==cp_B&&cp_B==cp_C)); //使用Class的newInstance创建此类的新实例 //newInstance将调用默认构造,所以私有的构造函数将导致错误 Object p_B = cp_C.newInstance(); //使用getDeclaredConstructors返回构造器集合并选择使用创建新实例 Constructor[] cons = cp_C.getDeclaredConstructors(); for(Constructor t : cons){ System.out.println(t); } //私有构造 必须设置权限 cons[0].setAccessible(true); Person p_C = (Person)cons[0].newInstance(true); p_C.getDescription(); //公共构造则不需要 p_C = (Person)cons[1].newInstance("Li",30); p_C.getDescription(); p_C = (Person)cons[2].newInstance(); p_C.getDescription(); }catch(ClassNotFoundException msg){ msg.printStackTrace(); }catch(InstantiationException msg){ msg.printStackTrace(); }catch(IllegalAccessException msg){ msg.printStackTrace(); }catch(InvocationTargetException msg){ msg.printStackTrace(); }finally{ //TODO://end } } } class Person{ private String Name; private int Age; public Person(){ this.Name = "Public: Default"; this.Age = 0; } public Person(String name,int age){ this.Name = "Public: "+name; this.Age = age; } private Person(boolean token){ if(token){ this.Name = "Private: Me"; this.Age = 0; }else{ this.Name = "Private: Other"; this.Age = -1; } } public static Person getPerson(){ return new Person(true); } public void getDescription(){ System.out.println(this.Name+" "+this.Age); } }
JAVA新手入门手稿——反射的初步认识
猜你喜欢
转载自blog.csdn.net/geekyoung/article/details/80257560
今日推荐
周排行