Summary of three methods for Java to obtain reflection mechanism


The concept of reflection mechanism:

In the running state, for any class, you can know all the properties and methods of this class, and for any object, you can call any of its methods. This kind of dynamic access to information and the function of dynamic call to object methods is called the java reflection mechanism

Application of reflection mechanism:

Generate dynamic proxy and program for slicing (add stack frame before and after calling method)

Principle of reflection mechanism:

The first clear concept: everything is an object — a class is an object

2 then know the content of the class: modifier constructor field method

Second, understand how to load: when animal.class is in the hard disk, it is a file. When it is loaded into memory, it can be regarded as an object, which is the object of java.lang.class

There are three ways to get reflection in Java:

1. Implement reflection mechanism through new object

2. Reflection mechanism through path

3. Implement reflection mechanism by class name

  • Get through the getClass method of the object class
  • How to use. Class
  • Using the class.forname method


Create a student class:

public class Student {
 private int id;
 String name;
 protected boolean sex;
 public float score; 

Get reflection mechanism

public class Get {
 //Three ways to acquire reflection mechanism
 public static void main(String[] args) throws ClassNotFoundException {
 //Mode 1 (by creating objects)
 Student stu = new Student();
 Class classobj1 = stu.getClass();
 //Mode 2 (passing path relative path)
 Class classobj2 = Class.forName("fanshe.Student");
 //Mode 3 (by class name)
 Class classobj3 = Student.class;


The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]