Java反射(1)Class类对象的获取


public class Main {

	public static void main(String[] args) {
		Student student = new Student();
		//获取class对象的三种方式
		Class a1 = Student.class;
		Class a2 = student.getClass();
		try {
			//写完整包名 且抛出异常
			Class a3=Class.forName("Student");
			System.out.println(a1);
			System.out.println(a2);
			System.out.println(a3);
			
			//根据class对象生成对象实例 前提是该类有无参的构造函数
			Student s1=(Student) a1.newInstance();
			Student s2=(Student) a2.newInstance();
			Student s3=(Student) a3.newInstance();

			s1.getResult();
			s1.getResult();
			s1.getResult();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
class Student{
	
	public Student() {
		super();
	}

	public void getResult() {
		System.out.println("getResult()");
	}
}

 

全部评论

相关推荐

shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
感性的干饭人在线蹲牛友:🐮 应该是在嘉定这边叭,禾赛大楼挺好看的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务