Java 反射 -- 实例对象的表示

Student的实例对象如何表示

Student s = new Student();.

第一种表示方式

实际在告诉我们任何一个类都有一个隐含的静态成员变量class
Class c1 = Student.class;

第二种表达方式

已经知道该类的对象通过getClass方法
Student s = new Student();
Class c2 = s.getClass();

第三种表达方式

Class c3 = Class.forName(“com.zhuoyue.test.Student”);//需要抛异常

Demo.java

package com.zhuoyue.test;

public class Demo {
    
    
	
	public static void main(String[] args) {
    
    
		
		Student s = new Student();
		
		Class c1 = Student.class;
		System.out.println(c1);
		
		Class c2 = s.getClass();
		System.out.println(c2);
		
		Class c3 = null;
		try {
    
    
			c3 = Class.forName("com.zhuoyue.test.Student");
			System.out.println(c3);
		} catch (ClassNotFoundException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
    
    
			Student s1 = (Student)c1.newInstance();
			s1.say();
		} catch (InstantiationException | IllegalAccessException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		try {
    
    
			Student s2 = (Student)c2.newInstance();
			s2.say();
		} catch (InstantiationException | IllegalAccessException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
    
    
			Student s3 = (Student)c3.newInstance();
			s3.say();
		} catch (InstantiationException | IllegalAccessException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

Student.java

package com.zhuoyue.test;

public class Student {
    
    
	
	public void say (){
    
    
		System.out.println("student");
	}
	
	private int id = 1;
	private String name = "hongzhe";
	
	public int getId() {
    
    
		return id;
	}
	public void setId(int id) {
    
    
		this.id = id;
	}
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	@Override
	public String toString() {
    
    
		return "Student [id=" + id + ", name=" + name + "]";
	}
	
}

猜你喜欢

转载自blog.csdn.net/xiaozhezhe0470/article/details/108807349
今日推荐