Java反射----获取Class类实例的4种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xd15010130025/article/details/88720206

第一种

调用运行时类本身的.class属性

Class clazz=Person.class;
		//创建class对应的运行时类Person对象
		System.out.println(clazz);
		Class clazz1=String.class;
		System.out.println(clazz1);

运行结果
在这里插入图片描述

第二种

运行时类的对象获取

Person p=new Person();
		Class clazz2=p.getClass();
		System.out.println(clazz2);

运行结果
在这里插入图片描述

第三种

通过Class的静态方法获取

String className="test.Person";
		Class clazz3=Class.forName(className);
		System.out.println(clazz3);

运行结果
在这里插入图片描述

第四种(了解)

通过类的加载器

ClassLoader classLoader=this.getClass().getClassLoader();
		Class clazz4=classLoader.loadClass(className);
		System.out.println(clazz4);

运行结果
在这里插入图片描述

总代码

public void test3() throws Exception {
		Class clazz=Person.class;
		//创建class对应的运行时类Person对象
		System.out.println(clazz);
		Class clazz1=String.class;
		System.out.println(clazz1);
		
		Person p=new Person();
		Class clazz2=p.getClass();
		System.out.println(clazz2);
		
		String className="test.Person";
		Class clazz3=Class.forName(className);
		System.out.println(clazz3);
		
		ClassLoader classLoader=this.getClass().getClassLoader();
		Class clazz4=classLoader.loadClass(className);
		System.out.println(clazz4);
	}

运行结果
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xd15010130025/article/details/88720206
今日推荐