Java 7 Reflection (2): Get class Object Information

Source: Internet
Author: User

Technorati Tag: java, reflection, class <T>

The first article on how to obtain class objects will continue to talk about how to obtain class Object Information. Class Object Information can be roughly divided into two categories: 1) class Object Information; 2) class Object member information.Class Object InformationIt mainly modifiers, generic parameters, Implemented interfaces, inherited paths and annotation information.Member information of the class ObjectIt mainly includes the member variable field, function method and constructor. Before entering the body, if you do not know much about the class information, you can refer to the java modifier overview.

1. Get class Object Information

To obtain information about a class object, we mainly use a series of corresponding function methods. Here we will give a brief introduction:

Method Description
GetCanonicalName () Obtain the class name
GetModifiers () Get the class Modifier
GetTypeParameters () Obtain generic parameters of a class
GetGenericInterfaces () Obtain the class implementation Interface
GetSuperclass () Obtain the parent class of the class. The inherited path can be obtained after multiple calls.
GetAnnotations () Get class Annotation

Appendix: 1. the above methods are the Function Methods of class objects. The method name with "s" indicates that one or more methods are returned in arrays. For example, "getTypeParameters () may return the Type [] array. Others are similar. Note that "getmodifiers)" returns an int. 2. getAnnotations) does not obtain all annotations of the class. Only annotations of java. lang. reflect. AnnotatedElement can be obtained. For example, in the three reserved annotations @ Override, @ Deprecate, and @ SuppressWarning, only @ Deprecate can be obtained.

The following is a Demo to demonstrate how to traverse the information of a class Object:

Public class ClassDeclarationSpy {public static void main (String [] args) {try {Class <?> C = Class. forName ("java. util. date "); out. println ("Class Name:" + c. getCanonicalName (); out. println ("Modifier:" + Modifier. toString (c. getModifiers (); out. print ("generic parameter:"); TypeVariable <?> [] TV = c. getTypeParameters (); if (TV. length! = 0) {for (TypeVariable <?> T: TV) out. print (t. getName () + ""); out. println ();} else {out. println ("no generic parameter");} out. print ("implemented interface:"); Type [] intfs = c. getGenericInterfaces (); if (intfs. length! = 0) {for (Type intf: intfs) out. println ("" + intf. toString ();} else {out. println ("unimplemented interface");} out. print ("inherited path:"); List <Class <?> L = new ArrayList <> (); assembleAncestor (c, l); if (l. size ()! = 0) {for (Class <?> Cl: l) out. println (cl. getCanonicalName ();} else {out. println ("No superclass");} out. print ("Annotation:"); Annotation [] ann = c. getAnnotations (); if (ann. length! = 0) {for (Annotation a: ann) out. print (. toString () + ""); out. format ("% n"); out. println ();} else {out. println ("no annotation") ;}} catch (ClassNotFoundException e) {e. printStackTrace () ;}} private static void assembleAncestor (Class <?> C, List <Class <?> L) {Class <?> Ancestor = c. getSuperclass (); if (ancestor! = Null) {l. add (ancestor); assembleAncestor (ancestor, l );}}}


The output is as follows:

650) this. width = 650; "style =" background-image: none; border-right-0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px "title =" image "border =" 0 "alt =" image "src =" http://www.bkjia.com/uploads/allimg/131228/151445E13-0.png "width =" 368 "height =" 165 "/>

Similarly, you can obtain information about java. util. List. The output is as follows:

650) this. width = 650; "style =" background-image: none; border-right-0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px "title =" image "border =" 0 "alt =" image "src =" http://www.bkjia.com/uploads/allimg/131228/151445B41-1.png "width =" 325 "height =" 150 "/>

Try to get an outdated class, such as java. io. StringBufferInputStream

650) this. width = 650; "style =" background-image: none; border-right-0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px "title =" image "border =" 0 "alt =" image "src =" http://www.bkjia.com/uploads/allimg/131228/151445F27-2.png "width =" 407 "height =" 185 "/>

2. Obtain the member information of the class Object

Member information of the class ObjectIt mainly includes member variables, function methods, and constructors. Similar to getting class Object Information, java provides various methods to obtain member information. These methods can be divided into two types. One is to directly obtain all member variables, functions, or constructors) the other is to search for a specified member. The following provides an overview of these methods:

1. Obtain the fields of the Class corresponding to the Class object.

ClassAPI

Inherited ??

Private ??

GetDeclaredField ()

No

Yes

GetField ()

Yes

No

GetDeclaredFields ()

No

Yes

GetFields ()

Yes

No

The explanation is as follows: "inherited ?" Indicates whether this method can obtain the filed value inherited from the superclass, and "private" indicates whether this method can obtain the private field; if the method contains "Declared", the field value contained in the class object is obtained. If not, the field of the super class can be obtained. If the method name contains "s" at the end, indicates that this method obtains all the field values that can be obtained and returns a Field <?> [] Array. Otherwise, it is used to obtain the specified field value, and Field <T> is returned. For example, "getDeclaredField ()" indicates to get the field contained in the current class object. This method can get the field value modified by private, "getfields) all public fields of the class object are inherited from the overage. private-modified fields cannot be obtained.

2. Obtain the Class method corresponding to the Class Object

ClassAPI

Inheritance Method?

Private Method?

GetDeclaredMethod ()

No

Yes

GetMethod ()

Yes

No

GetDeclaredMethods ()

No

Yes

GetMethods ()

Yes

No

3. Obtain the constructor of the Class Object.

ClassAPI

Inherited?

Private?

GetDeclaredConstructor ()

--

Yes

GetConstructor ()

--

No

GetDeclaredConstructors ()

--

Yes

GetConstructors ()

--

No

Because the constructor cannot inherit from the superclass, inheritance does not have any meaning for the constructor. Other usage is similar to the method for obtaining the field.

Demo: create two classes: Student and Bachelor.

package com.other;public class Student {private int id;private String sex;public String name;public Student() {}public Student(int id, String sex, String name) {super();this.id = id;this.sex = sex;this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
package com.other;public class Bachelor extends Student{private String major;public Bachelor() {}public Bachelor(String major) {super();this.major = major;}}


Use ClassHelp to output the member information of the class Object

Public class ClassHelp {public static void main (String [] args) throws Exception {Student stu = new Bachelor ("computer"); Class <?> Clazz = stu. getClass (); // name of the output class System. out. println ("class name:" + clazz. getName (); // output the System of the class package. out. println ("class package:" + clazz. getPackage (); // obtain the specified fieldSystem. out. println (clazz. getField ("name"); // printMembers (clazz. getFields (), "Fields"); // printMembers (clazz. getDeclaredConstructors (), "Constructors"); // printMembers (clazz. getMethods (), "methods");} public static void printMembers (Member [] mb Rs, String s) {// Field, mehtodd, and constructor are all out implementations of Member. println (s); for (Member mbr: mbrs) {if (mbr instanceof Field) out. println (Field) mbr ). toGenericString (); else if (mbr instanceof Constructor) out. println (Constructor <?>) Mbr ). toGenericString (); else if (mbr instanceof Method) out. println (Method) mbr ). toGenericString ();} if (mbrs. length = 0) out. println ("nonexistent" + s); out. println ();}}


Although the ClassHelp code is simple, it also demonstrates how to access the information of class Object members. Its output is as follows:

650) this. width = 650; "style =" background-image: none; border-right-0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px "title =" image "border =" 0 "alt =" image "src =" http://www.bkjia.com/uploads/allimg/131228/151445AN-3.png "width =" 531 "height =" 105 "/>

The output of the other three lines of annotation code is as follows:

650) this. width = 650; "style =" background-image: none; border-right-0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px "title =" image "border =" 0 "alt =" image "src =" http://www.bkjia.com/uploads/allimg/131228/15144534R-4.png "width =" 536 "height =" 250 "/>

There should be no problem with the output of Field and Constructors, but the output of Method is much more "unexpected" information. In fact, these inherited methods-in java, any object is java, lang. object directly or indirectly subclass, so getMethods () also corresponds to java in the output. The nine methods of lang. Object.

Method toGenericString) returns the description of this member Filed. Method, Constructor) generic description. If it does not exist, toString () is called to return the member Filed. Method, Constructor) string.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.