Java Reflection Demo

Source: Internet
Author: User

Class-Based reflection class objects provide you with all the basic hooks for the reflection of the access class metadata. Such metadata includes information about the class itself, such as the parent class of the package and class, and the interfaces that the class implements. It also includes details about the constructors, fields, and methods defined by the class.
These final projects are the most frequently used projects in programming, so I'll give you some examples of how to collaborate with them later in this section. For any of the following three categories of components--constructors, fields and methods--Java.lang.Class provides four independent reflection calls to obtain information in different ways. Calls follow a standard format. The following is a set of reflection calls for finding constructors: Constructor GetConstructor (class[] params)--get public constructors that use special parameter types, constructor[] getconstructors ()--get all public constructors for class constructor Getdeclaredconstructor (class[] params)--get a constructor that uses a specific parameter type (regardless of access level) constructor[] getdeclaredconstructors ()--get all constructors for a class (regardless of access level) Each class of these calls returns one or more Java.lang.reflect.Constructor functions. This Constructor class defines the Newinstance method,
It takes a set of objects as its only parameter, and then returns the newly created instance of the original class. The group object is the parameter value used to construct the function call.
As an example of explaining this workflow, suppose you have a twostring class and a constructor that uses a pair of string s, as shown in Listing 1: Listing 1: Class created from a pair of strings& #1601234567 Public classtwostring {PrivateString m_s1, m_s2; Publictwostring (string s1, string s2) {m_s1=S1; M_s2=S2; }} The code in Listing 2 gets the constructor and uses it to create a String s using the"A" and "B"An example of the Twostring class: Listing 2: Reflection invocation of the constructor1234class[] Types=NewClass[] {String.class, String.class }; Constructor Cons= twostring.class. GetConstructor (types); object[] args=NewObject[] {"A", "B" }; twostring TS= Cons.newinstance (args);


--------even though they come from the ancestor class. The latter two variables return information about the fields declared directly by the class-- regardless of the access type of the field. Calling the returned Java.lang.reflect.Field instance defines the GetXXX and Setxxx methods for all the main types, as well as common get and set methods for collaborating with object references.
You can choose an appropriate method based on the actual field type, and the GetXXX method will automatically handle the extended transformation (such as using the GetInt method to retrieve a byte value).

 Public classEmployee {Private intID;PrivateString name; Public intgetId () {returnID;} Public voidSetId (intID) { This. ID =ID;} PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;} Publicemployee () {Super(); //TODO auto-generated Constructor stub} PublicEmployeeintID, String name) {    Super();  This. ID =ID;  This. Name =name;}}
ImportJava.lang.reflect.Field; Public classApp { Public intIncrementfield (String name, Object obj)throwsException {Field field=Obj.getclass (). Getdeclaredfield (name); Field.setaccessible (true); Open private access and modify the value of the fieldintValue = Field.getint (obj) + 1;        Field.setint (obj, value); returnvalue; }         Public Static voidMain (string[] args)throwsException {app A1=Newapp (); intX=a1.incrementfield ("id",NewEmployee ("Xiaoming")); SYSTEM.OUT.PRINTLN (x);}}

For example, if the object is an integer count value that defines the GetCount and SetCount methods, you can increase the value by passing "Count" as the name parameter to the method in a single call. Listing 4: Adding a JavaBean property by reflection1234567891011121314 Public intIncrementproperty (string name, Object obj) {string prop= Character.touppercase (Name.charat (0)) +name.substring (1); String Mname= "Get" +prop; Class[] Types=Newclass[] {}; Method Method=Obj.getclass (). GetMethod (Mname, types); Object result= Method.invoke (obj,NewObject[0]); intValue = ((Integer) result). Intvalue () + 1; Mname= "Set" +prop; Types=NewClass[] {int.class }; Method=Obj.getclass (). GetMethod (Mname, types); Method.invoke (obj,NewObject[] {NewInteger (value)}); returnvalue;} In order to follow the JavaBeans convention, I changed the first letter of the property name to uppercase and then pre-considered get to create the Read method name, set to create the Write method name. The JavaBeans Read method returns only the value, and the Write method uses the value as the unique parameter.
So I specify the parameter type of the method to match. Finally, the Convention requires the method to be public, so I use the Find format to find public methods that can be called on the class. This is the first instance where I pass the primary value using reflection, so let's look at how it works.
The basic principle is simple: whenever you need to pass a primary value, you simply replace that class's primary value with an instance of the enclosing class (defined in the Java.lang package). This can be applied to calls and returns.
, so when I call the Get method in the instance, I expect the result to be actualintThe Java.lang.Integer encapsulation of the property value.

An array of reflected arrays is an object in the Java programming language. As with all objects, they all have classes. If you have an array that uses the standard GetClass method, you can get the class of the array, just like any other object.
However, you do not use an existing instance to obtain a class that differs from other types of objects. Even if you have an array class, you cannot do too much of it directly--the constructor that the reflection provides to the standard class cannot be used for arrays,
And the array does not have any accessible fields, only the basic Java.lang.Object method definition is used for the array object. The special handling of arrays uses the collection of static methods provided by the Java.lang.reflect.Array class. The methods in this class enable you to create a new array, get the length of the array object, and read and write the indexed values of the array object. Listing 5 shows an efficient way to resize an existing array. It uses reflection to create a new array of the same type, and then copies all the data in the old array before returning the new array. Checklist5: Extend an array by reflection1234567 PublicObject Growarray (Object array,intsize) {Class type=Array.getclass (). Getcomponenttype (); Object Grown=array.newinstance (type, size); System.arraycopy (Array,0, grown, 0, Math.min (Array.getlength (Array), size); returngrown;}
Listing 8: Method Access performance Test code Public intCalldirectargs (intloops) {    intValue = 0;  for(intindex = 0; Index < loops; index++) {Value=step (value); }    returnvalue; Use direct variables for operations, evaluate directly and return values} Public intCallreferenceargs (intloops) {Timingclass Timing=NewTimingclass (); intValue = 0;  for(intindex = 0; Index < loops; index++) {Value=Timing.step (value); }    returnvalue; Use the fields of the class to perform operations, evaluate and return values} Public intCallreflectargs (intLoopsthrowsException {timingclass timing=NewTimingclass (); Try{Method Method= Timingclass.class. GetMethod ("Step",NewClass [] {int.class }); Object[] args=NewObject[1]; Object value=NewInteger (0);  for(intindex = 0; Index < loops; index++) {//Use reflection fields for operations, evaluate and return values. args[0] =value; Value=method.invoke (timing, args); }        return((Integer) value). Intvalue (); } Catch(Exception ex) {System.out.println ("Error Using Reflection"); Throwex; }}

Java Reflection Demo

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.