java基础 之 获取class类 对象的 4 种 方式

package com.test.chin;

import static org.junit.Assert.*;

import org.junit.Test;

import com.test.chin.bean.User;

public class createClass {

	// 获取class类  对象的 4 种 方式
	@Test
	public void test() {
		
		// 调用运行时类的本身
		Class class1 = User.class;
		System.out.println(class1.getName());
		
		// 调用运行时类的对象
		User user2 = new User();
		Class class2 = user2.getClass();
		System.out.println(class2.getName());
		
		// 通过类的静态方法来获取
		try {
			Class class3 = Class.forName("com.test.chin.bean.User");
			System.out.println(class3.getName());
		} catch (ClassNotFoundException e) {
		}
		
		// classloader 类的加载器
		ClassLoader classLoader = this.getClass().getClassLoader();
		try {
			Class class4 = classLoader.loadClass("com.test.chin.bean.User");
			System.out.println(class4.getName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
发布了42 篇原创文章 · 获赞 1 · 访问量 5390

猜你喜欢

转载自blog.csdn.net/MENGCHIXIANZI/article/details/105015545