java反射三种获得类类型的方法

public class Test {
	public static void main(String[] args) {
		Test t=new Test();//所有的类都是Class类的实例(类类型)
		Class c1=Test.class;//第一种通过类型的class(静态变量)
		Class c2=t.getClass();//第二种通过对象实例的方法getClass();
		Class c3=null;
		try {
			 c3=Class.forName("test1.Test");//通过Class的静态方法forName();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			Test t2=(Test) c3.newInstance();//通过Class的newInstance()创建实例
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//
		System.out.println(c1==c2);//true
		System.out.println(c2==c3);//true
	}
}

posted on 2017-11-13 15:48  天生一对  阅读(532)  评论(0编辑  收藏  举报

导航