【Java笔记】创建Class对象的三种常用办法和Class单例的测试

package Test_01;

import org.junit.Test;


public class Test_01 {
	@Test
	public void Dome(){
		//通过class属性获取,最为可靠,程序安全性最高
	Class cc=Cat.class;
	System.out.println(cc.getSuperclass());
	System.out.println(cc.getName());
	System.out.println(cc.getSimpleName());	
	System.out.println(cc.getSuperclass());
}
	@Test
	public void Dome_02(){
		//先创建一个Cat对象,用对象的getclass方法调用
		Cat cat=new Cat();
		Class cc=cat.getClass();
		System.out.println(cc.getSuperclass());
		System.out.println(cc.getName());
		System.out.println(cc.getSimpleName());	
		System.out.println(cc.getSuperclass());
	}
	@Test
	public void Dome_03() throws ClassNotFoundException{
		//通过Class对象的forName()方法获取,但可能会抛出路径找不到类的异常
		Class cc=Class.forName("Test_01.Cat");
		System.out.println(cc.getSuperclass());
		System.out.println(cc.getName());
		System.out.println(cc.getSimpleName());	
		System.out.println(cc.getSuperclass());

	}
	@Test
	//验证Class类只有一个对象
	public void Dome_04() throws ClassNotFoundException{
		Class cc1=Cat.class;
		Cat cat=new Cat();
		Class cc2=cat.getClass();
		Class cc3=Class.forName("Test_01.Cat");
		System.out.println(cc1==cc2);
		System.out.println(cc2==cc3);
	}	
	public void Dome_05(){
		Class cc1=Cat.class;
		
	}
}

package Test_01;

public class Animals {
	String name;
	String age;
}

package Test_01;

public class Cat extends Animals{
	 String name;
	 int age;
	 int legs;
	
}

输出结果前三个dome是一致的:

class Test_01.Animals
Test_01.Cat
Cat
class Test_01.Animals

最后一个:

true
true

说明Class只能有一个对象,是单例的


你可能感兴趣的:(【学习笔记】)