Home> Java> javaTutorial> body text

How to get objects using java reflection

PHPz
Release: 2023-05-15 12:46:06
forward
1524 people have browsed it

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); }
Copy after login

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类的字节码 }
Copy after login

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); }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!