Java reflection - representation of instance objects

How to represent the instance object of Student

Student s = new Student();.

The first way of expression

Actually telling us that any class has an implicit static member variable class
Class c1 = Student.class;

The second way of expression

It is already known that objects of this class pass the getClass method
Student s = new Student();
Class c2 = s.getClass();

The third way of expression

Class c3 = Class.forName("com.zhuoyue.test.Student");//Need to throw an exception

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 + "]";
	}
	
}

Guess you like

Origin blog.csdn.net/xiaozhezhe0470/article/details/108807349