1. Use the object to call the getClass method of Object
Method to obtain the bytecode object: To use this method, you must clarify the specific category and create the object.
public static void getClassObject_1() { Person p = new Person(); Class> clazz = p.getClass(); Person p1 = new Person(); Class> clazz1 = p1.getClass(); System.out.println(clazz == clazz1); }
2、Calling properties
Any data type has static properties. class can obtain the corresponding class object. Relatively simple, but explicitly use static members in the class.
public static void getClassObject_2() { Class> clazz = Person.class; Class> clazz1 = Person.class; System.out.println(clazz == clazz1);//true都是Person类的字节码 }
3. Using the forName() method
can be obtained by the string name of a given category, and can be more expanded. But it is done in Class class. This method is forName. This method only needs a name, which is more convenient and extensible.
public static void getClassObject_3() throws ClassNotFoundException { String className = "com.ldb.po.Person"; Class> clazz = Class.forName(className); System.out.println(clazz); }
The above is the detailed content of How to get objects using java reflection. For more information, please follow other related articles on the PHP Chinese website!