How to obtain Class structure Information by reflection in Java
Editor to share with you Java reflection how to obtain class structure information, I hope you will learn something after reading this article, let's discuss it together!
Reflection acquires class structure information
In the process of the reflection mechanism, it is not only the processing operation of instantiating the object, but also the composition structure operation of the class. the basic structure of any class is parent class (parent interface), package, attribute, method (constructor, common method).
Get the basic information of the class
The basic information of a class mainly includes the package name of the class, the definition of the parent class, and the definition of the parent interface.
Example: define a program class
IMessageService:
Interface IMessageService {public void send ();}
IChannelService:
Interface IChannelService {public boolean connect ();}
AbstractBase:
Public abstract class AbstractBase {}
Person:
Public class Person extends AbstractBase implements IChannelService,IMessageService {@ Overridepublic boolean connect () {return true;} @ Overridepublic void send () {if (this.connect ()) {System.out.println ("[message sending] www.mldn.cn");}
If you want to get some basic information about this class at this time, you can use the following methods in the Class class:
1. Get the package name: public Package getPackage ()
2. Get the inheritance parent class: public Class [] getInterfaces ()
Example: get the package name
Public class JavaAPIDemo {public static void main (String [] args) {Class cls = Person.class;// get the Class object Package pack = cls.getPackage () of the specified class; / / get the package definition System.out.println (pack.getName ()) of the specified class; / / get the package name}}
Example: get parent class information
Public class JavaAPIDemo {public static void main (String [] args) {Class cls = Person.class;Class parent = cls.getSuperclass (); / / get the Class object System.out.println (parent.getName ()) of the specified class; System.out.println (parent.getSuperclass (). GetName ()); / / System.out.println (parent.getSuperclass (). GetSuperclass ());}}
Example: get the parent interface
Public class JavaAPIDemo {public static void main (String [] args) {Class cls = Person.class; / / get the Class object Class clazz of the specified class [] = cls.getInterfaces (); / / get the Class object for (Class temp: clazz) {System.out.println (temp.getName ()) of the parent interface; / / get the object name of the parent interface}
When you get the Class object of a class, it means that the object can get all the inheritance structure information in the class.
After reading this article, I believe you have a certain understanding of "how to obtain class structure information in Java". If you want to know more about it, please follow the industry information channel. Thank you for reading!