Java Basics (11) Java reflection mechanism (TOP)

Source: Internet
Author: User

Java.lang.Class class explanation

Java class explanation

first, class

Class is an implementation of a specific class defined by the Java language, in which each class has a corresponding class object so that the Java program Runtime System (JVM) performs a run-time type identification of all objects, that is, the class object, The JVM can manipulate the corresponding class through the object (such as selecting the correct method to execute).

The class class is used to encapsulate information about a class (class or interface) that is loaded into the JVM (class name, type belongs to class, interface, enum, or annotation), which is the basis of the Java reflection mechanism, and we can obtain information about a class through class Classes.

When the program runs, if an object needs to be generated, the JVM first detects whether the Class's class object is loaded (as described later in the Class's loading), and if not, the JVM will look up The. class file based on the file name to load it to create the required instance. The JVM manages a unique class object for each class (provided that the same ClassLoader is used).

The base data types (boolean, byte, char, short, int, long, float, and double) and the keyword void also correspond to a class Object. In addition, each array belongs to a class that is mapped to a class object, and all arrays that have the same element type and number of dimensions share the class Object.

Class has no public constructor method. Class objects are constructed automatically by the Java virtual machine when the class is loaded and by invoking the DefineClass method in the classloader, so you cannot explicitly declare a class Object.

1. Three ways to get the class object corresponding to a category

To access the class information encapsulated by a class object in the jvm, we first get the class object of the corresponding classes, which we can do in the following three ways:

a, obtained through the GetClass () method of Object (all Java objects have this METHOD)

b, the use of The. class method (using the class name plus ". class" will return the class object corresponding to it, do not need to create the object of the Class)

c, Use the Class.forName () method, which obtains the class object associated with the class (string, including the package where the class resides, such as Com.baidu.User).

Here is a sample code:

 public classObtainclass { public Static voidmain (string[] Args) {Try{String str1= "abc"; System.out.println ("get by using the GetClass () method of object:" +Str1.getclass ()); System.out.println ("get by Using. class:" + String.class); System.out.println ("use the Class.forName () method to get:" + Class.forName ("java.lang.String")); System.out.println (str1.getclass ()= = String.class); System.out.println (str1.getclass ()= = Class.forName ("java.lang.String")); } Catch(classnotfoundexception E) {e.printstacktrace (); }    }}

As you can see from the code above, each class corresponds to a unique class Object.

2. Common Methods of Class

 public classClasstest { public Static voidmain (string[] Args) {Try{System.out.println ("returns the class object associated with the classes or interfaces with the given string name:" + Class.forName ("com.classTest.classload.CTest")); System.out.println ("returns the name of the entity (class, interface, array class, base type, or Void) represented by this class object as a String:" + class.forname ("com.classTest.classload.CTest"). GetName ()); System.out.println ("get packages of this class:" + class.forname ("com.classTest.classload.CTest"). getpackage ()); System.out.println ("returns the class object associated with the classes or interfaces with the given string name using the given class loader:" + Class.forName ("com.classTest.classload.CTest",true, Classloader.getsystemclassloader ())); System.out.println ("returns the class of the superclass that represents the entity (class, interface, Base type, or Void) represented by this class:" + class.forname ("com.classTest.classload.CTest"). Getsuperclass ()); System.out.println ("returns the short name of the underlying class given in the source code:" + class.forname ("com.classTest.classload.CTest")). Getsimplename ()); System.out.println ("get tags for this class:" + class.forname ("com.classTest.classload.CTest"). getsigners ()); CTest CT=NewCTest (); System.out.println ("if a comment of the specified type exists for the element, the comments are returned, otherwise null:" +Ct.annotationtype ()); System.out.println ("returns the canonical name of the underlying class as defined in Java Language specification:" + class.forname ("com.classTest.classload.CTest"). Getcanonicalname ()); System.out.println ("returns an array containing some class objects that represent all public classes and interfaces that belong to the members of the class represented by this class object:" + Class.forName ("com.classTest.classload.CTest"). getclasses ()); System.out.println ("returns the class loader for this class:" + class.forname ("com.classTest.classload.CTest")). getClassLoader ()); System.out.println ("returns the Class that represents the array component type:" + class.forname ("com.classTest.classload.CTest"). Getcomponenttype ()); System.out.println ("returns a Constructor object that reflects the specified public construction method for the class represented by this class object:" + Class.forName ("com.classTest.classload.CTest")); System.out.println ("returns an array containing some Constructor objects that reflect all public constructors of the class represented by this class object:" + Class.forName ("com.classTest.classload.CTest"). getconstructors (). length); System.out.println ("returns A Field object that reflects the specified declared field of the class or interface represented by this class object:" + class.forname ("com.classTest.classload.CTest"). Getdeclaredfield (" Age). GetName ()); System.out.println ("returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object:" + Class.forName ("com.classTest.classload.CTest"). getdeclaredfields (). length); System.out.println ("returns A Field object that reflects the specified public member field for the class or interface represented by this class object:" + class.forname ("com.classTest.classload.CTest"). GetField ("str")); System.out.println ("returns an array containing some field objects that reflect all accessible public fields for the class or interface represented by this class object:" + Class.forName ("com.classTest.classload.CTest"). getfields (). length); System.out.println ("returns a method object that reflects the specified declared method for the class or interface represented by this class object:" + class.forname ("com.classTest.classload.CTest"). getdeclaredmethod ("annotationtype"). GetName ()); System.out.println ("returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods:" + class.forname (" Com.classTest.classload.CTest "). getdeclaredmethods (). length); System.out.println ("if This class object represents a local or anonymous class in a method, the method object is returned, which represents the immediate closure of the underlying class:" + class.forname ("com.classTest.classload.CTest"). Getenclosingmethod ()); System.out.println ("returns a method object that reflects the specified public member methods for the class or interface represented by this class object:" + class.forname ("com.classTest.classload.CTest"). getmethod (" Annotationtype ")); System.out.println ("returns an array containing some method objects that reflect the public member method of the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface:" + class.forname (" Com.classTest.classload.CTest "). getmethods (). length); System.out.println ("returns the Java language modifier with integer encoding for this class or interface:" + Class.forName ("com.classTest.classload.CTest"). getmodifiers ()); System.out.println ("returns true if this Class object represents a comment type:" + class.forname ("com.classTest.classload.ETest"). isannotation ()); System.out.println ("returns true when and only if the underlying class is an anonymous class:" + class.forname ("com.classTest.classload.ETest"). Isanonymousclass ()); System.out.println ("determines whether this class object represents an array class:" + class.forname ("com.classTest.classload.ETest")). IsArray ()); System.out.println ("determines whether the class or interface represented by this class object is the same as the class or interface represented by the specified class parameter, or whether it is a superclass or a hyper-interface:" + class.forname ("com.classTest.classload.ETest"). IsAssignableFrom (class.forname ("com.classTest.classload.ETest"))); System.out.println ("returns true when and only if the class is declared as an enumeration in source code:" + class.forname ("com.classTest.classload.ETest"). Isenum ()); System.out.println ("determines whether the specified object is compatible with the value represented by this Class:" + class.forname ("com.classTest.classload.CTest"). isinstance (class.forname (" Com.classTest.classload.CTest "). newinstance ())); System.out.println ("determines whether the specified Class object represents an interface type:" + class.forname ("com.classTest.classload.CTest"). isinterface ()); System.out.println ("returns true when and only if the underlying class is a local class:" + class.forname ("com.classTest.classload.CTest"). Islocalclass ()); System.out.println ("returns true when and only if the underlying class is a member class:" + class.forname ("com.classTest.classload.CTest"). Ismemberclass ()); System.out.println ("determines whether the specified Class object represents a basic type:" + class.forname ("com.classTest.classload.CTest"). isprimitive ()); System.out.println ("returns true if this class is a composite class, otherwise false:" + class.forname ("com.classTest.classload.CTest"). issynthetic ()); System.out.println ("create a new instance of the class represented by this class object:" + Class.forName ("com.classTest.classload.CTest"). newinstance (). toString ()); } Catch(classnotfoundexception E) {e.printstacktrace (); } Catch(nosuchfieldexception E) {e.printstacktrace (); } Catch(nosuchmethodexception E) {e.printstacktrace (); } Catch(instantiationexception E) {e.printstacktrace (); } Catch(illegalaccessexception E) {e.printstacktrace (); }    }}classCTestImplementsannotation{Private intage ; PrivateString name;  publicString str;  publicclass<?extendsAnnotation>annotationtype () {returnCtest.class; } @Override publicString toString () {return"ctest{" + "age=" + age + ", name= ' +" + name + ' \ ' + ", str= ' + str + ' + ' + ‘}‘; }}enumetest{CN, EN}

second, Method Class

  MethodProvides information about a single method (and how to access the METHOD) on a class or interface. The method that is reflected may be a class method or an instance method, including an abstract method.

 public classMethodtest { public Static voidMain (string[] Args)throwsException {Class clazz= Class.forName ("com.classTest.classload.MT"); method[] m=Clazz.getmethods ();  for(Method mh:m) {System.out.print (mh.getname ()+ "|" + mh.getdefaultvalue () + "|" +Mh.getreturntype ()); class[] C=Mh.getparametertypes (); System.out.print (" | Len = "+ c.length +" | ");  for(Class tv:c) {System.out.print ("  " +Tv.getname ());        } System.out.println (); } Method= Clazz.getmethod ("mt", String.class); Method.invoke (clazz.newinstance (),"test method");//invokes the underlying method represented by this method object for the specified object with the specified argument    }}classMT { publicstring Mt (string str) {System.out.println (str); returnstr; }}

third, Field Class

  FieldProvides information about a single field of a class or interface, as well as its dynamic access Rights. The reflected field may be a class (static) field or an instance Field.

 public classFieldtest { public Static voidMain (string[] Args)throwsException {Class clazz= Class.forName ("com.classTest.classload.FT"); field[] F=Clazz.getfields ();  for(Field fd:f) {System.out.println (fd.getname ()+ "|" + fd.gettype () + "|" + fd.getmodifiers () + "|" + fd.get ("")); }    }}classft{ public StaticString name = "name";  public Static intAge = 11;}

Java Basics (11) Java reflection mechanism (TOP)

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.