Java reflex mechanism

xiaoxiao2021-03-06  20

According to my understanding, the reflection mechanism is just the functions of Java providing class information. Many frameworks use this technology, but usually we use very little. However, this feature does not know when the class is runtime, and it can also obtain public methods in the class, and so on.

I want to sum up some usage, and then discover an article, from:

LXBLG's blog, I write it myself, I have not so detailed, still reprint it.

============================================================================================================================================================================================================= =========================

Lesson: Detection EXAMING CLASS

1. RETRIEVING CLASS Objects Gets a Class object (Metadata)

A, get from an instance of an object. Class c = mystery.getClass (); // ((Return Class) B, acquiring textfield t = new textfield (); class c = t.getClass (); C = c.getusuperclass (); c , Know the class name, you can get .class to get the name after the name. Class C = java.awt.button.class; d, if the class name is unknown at compile, you can use the class.forname () method to get .class c = class.Forname (ClassString);

2.Getting the class name Get class name C.GetName ();

For example: Import java.lang.reflect. *; Import java.awt. *;

Class Samplename {

Public static void main (string [] args) {button b = new button (); printname (b);}

Static void printname (Object O) {class c = o.getClass (); string s = c.getname (); system.out.println (s);}}

3. Discovering Class Modifiers Retrieves the modifier a. Get a integer identifier value via the getModifiers () method. b. Judging this value via Java.Reflect.Modifier object's ISPUBLIC, ISABSTRACT, and ISFinal methods.

For example: Import java.lang.reflect. *; Import java.awt. *;

Class SampleModifier {

Public static void main (string [] args) {string s = new string (); printmodifiers (s);}

Public Static Void PrintModifiers (Object O) {Class C = O.getClass (); INT M = C.getModifiers (); if (Modifier.Ispublic (m)) System.out.Println ("public"); if (Modifier); IF .issabstract (m)) System.out.println ("Abstract"); if (Modifier.isfinal (m)) System.out.Println ("Final");}} 4.Finding SuperClasses Checking the father class, for example: import Java .lang.reflect. *; import java.awt. *;

Class Samplesuper {

Public static void main (string [] args) {button b = new button (); printsuperclasses (b);}

static void printSuperclasses (Object o) {Class subclass = o.getClass (); Class superclass = subclass.getSuperclass (); while (superclass = null!) {String className = superclass.getName (); System.out.println (className ); Superclass = superclass; superclass = subsclass.getsuperclass ();}}}

5.Identifying the interfaces implemented by a class Retrieves the interface implementation interface, for example: import java.lang.reflect. *; Import java.io. *;

Class sampleInterface {

Public static void main (string [] args) {try {randomaccessfile r = new randomaccessfile ("myfile", "r"); printinterfacenames (r);} catch (ioException e) {system.out.println (e);} }

Static void printinterfacenames (object o) {class c = o.getClass (); class [] theinterface = c.GetInterface (); for (int i = 0; i

Import java.lang.reflect. *; import java.util. *;

Class SampleCheckInterface {

public static void main (String [] args) {Class thread = Thread.class; Class runnable = Runnable.class; verifyInterface (thread); verifyInterface (runnable);} static void verifyInterface (Class c) {String name = c.getName (); If (C.ISinterface ()) {System.out.println (Name "is an interface.");} Else {system.out.println (Name "is a class.");}}}

Suisi: c.isinterface ()

7.Identifying class Fields Find out specified class All Domain Members Each data can use java.reflect.field to enclose its name, type, and modifier. You can also acquire or set to the value of the member through the corresponding method. Import java.lang.reflect. *; Import java.awt. *;

Class samplefield {

Public static void main (string [] args) {gridbagconstraints g = new gridbagconstraints (); printfieldnames (g);}

Static void printfieldnames (object o) {class c = o.getClass (); field [] publicfields = c.Getfields (); for (int i = 0; i

8. Discovering Class Constructors Retrieves the constructor of the specified class

When an instance of a class is created, this method can be overloaded by a method of searching. Each constructor can be described by class constructor, including name, modifier, parameter type (class []), and exception list. You can get the constructor array of this class through a Class's getConstructors method. Routines: import java.lang.reflect. *; Import java.awt. *;

Class sampleconstructor {

Public static void main (string [] args) {Rectangle R = new Rectangle (); showconstructors (r);}

Static void showconstructors (Object O) {Class C = O.getClass (); Constructor [] theconstructors = c.getconstructors (); for (int i = 0; i

Routine:

Import java.lang.reflect. *; import java.awt. *;

Class SampleMethod {

Public static void main (string [] args) {polygon p = new polygon (); showMethods (p);}

Static void showMethods (Object O) {class c = o.getclass (); method [] themeth 4 = c.getMethods (); for (int i = 0; i

/ /.. Load classname from the user interface

Object o = new (classname); // Wrong!

But the above is wrong. The correct way is to use the reflection characteristics of the class:

1) using no-argument constructors, for example: class classdefinition = class.forname (classname); // Specify the running period of the class Object = classdefinition.newinstance (); // Call the unintegrated constructor to generate an instance of the specified class.

2) Using Constructors That Have Arguments This technology is to be used as follows: A. Create a Class object B. Create a constructor object, getConstructor (Class [] params) method, the parameter is a suitable class array that is suitable for constructor. The NewInstance method is called on the Constructor object to generate an object, and the parameter is an Object array equipped with this constructor. For example: Import java.lang.reflect. *; Import java.awt. *;

Class SampleInstance {

Public static void main (String [] args) {

Rectangle Rectangle; Class Rectangledefinition;

Class [] INTARGSCLASS = new class [] {int.class, int.class}; integer height = new integer (12); integer width = new integer (34); object [] idargs = new object [] {height, width }

Constructor INTARGSCONSTRUCTOR;

Try {// 1. Rectangledefinition = Class.Forname ("java.awt.rectangle"); // 2. INTARGSCONSTRUCTOR = Rectangledefinition.getConstructor (intargsclass); // Find specified constructor //3. Rectangle = (Rectangle) createObject (intArgsConstructor, intArgs); // constructor described objects, object []} catch (ClassNotFoundException e) {System.out.println (e);} catch (NoSuchMethodException e) {System.out.println (e);} }

Public Static Object CreateObject (Constructor Construction, Object [] arguments) {

System.out.println ("Constructor:" Constructor.toToString ()); Object Object = NULL;

try {object = constructor.newInstance (arguments); System.out.println ( "Object:" object.toString ()); return object;} catch (InstantiationException e) {System.out.println (e);} catch (IllegalAccessException e) {System.out.println (e);} catch (IllegalArgumentException e) {System.out.println (e);} catch (InvocationTargetException e) {System.out.println (e);} return object; }}2. Getting Field Values ​​if you are Writing a development Tool Such as a debugger, you must be able to obtain Field Values. This is a three-step process: If you want to make a development tool like Debugger, you have to find filed values The following is three steps: a. Create a Class object b. Create a field object with GetField C. Call the field.getxxxx (Object) method (xxx is int, float, if it is an object; Object means instance) .

For example: Import java.lang.reflect. *; Import java.awt. *;

Class sampleget {

Public static void main (string [] args) {Rectangle R = New Rectangle (100, 325); PrintHeight (R);

}

static void printHeight (Rectangle r) {Field heightField; Integer heightValue; Class c = r.getClass (); try {heightField = c.getField ( "height"); heightValue = (Integer) heightField.get (r); System. Out.println ("HEIGHT:" HeightValue.Tostring ());} catch (nosuchfieldException e) {system.out.println (e);} catch (securityExcect e) {system.out.println (e);} catch (IllegaCcessException E) {system.out.println (e);}}}

3. Setting Field Values ​​a. Create a Class object b. Create a Field object with GetField C. Call the field.Set (Object, WithParam) method (xxx is int, float, if it is an object; Object refers to the instance, withparam finger And the fields with this field.

Import java.lang.reflect. *; import java.awt. *; class sampleset {

Public static void main (string [] args) {Rectangle R = New Rectangle (100, 20); System.out.println ("Original:" R.TOString ()); ModifyWidth (R, New Integer (300)) System.out.println ("Modified:" R.toString ());

static void modifyWidth (Rectangle r, Integer widthParam) {Field widthField; Integer widthValue; Class c = r.getClass (); try {widthField = c.getField ( "width"); widthField.set (r, widthParam);} catch (NosuchfieldException E) {system.out.println (e);} catch (illegalaccessexception e) {system.out.println (e);}}}

4. Call the specified method a. Create a Class object b. Create a method object Method, getMethod (String methodname, class []) method c. Method object, method.invoke (object, object []), two parameters, One is the object belonging to the method, the second is the list of passed value objects.

The sample program that follows shows you how to invoke a method dynamically. The program retrieves the Method object for the String.concat method and then uses invoke to concatenate two String objects. //

Import java.lang.reflect. *;

Class sampleinvoke {

Public static void main (String [] args) {string firstword = "hello"; // Specify the instance of the class

String secondword = "Everybody."; //

String Bothwords = append (firstword, secondword); system.out.println (Bothwords);

转载请注明原文地址:https://www.9cbs.com/read-58947.html

New Post(0)