Java reflection (Java reflection) (2)

Source: Internet
Author: User
Once this information is obtained, you can perform Step 3-use the reflection API to perform such operations, as shown in the following code:

Class C = Class. forname ("Java. Lang. String ");

Method M [] = C. getdeclaredmethods ();

System. Out. println (M [0]. tostring ());

It prints the prototype of the first method defined in string in text format.

In the example below, these three steps will provide examples for Using Reflection to process special applications.

Simulate the instanceof Operator

After getting the class information, the next step is to solve some basic problems about the class object. For example, the class. isinstance method can be used to simulate the instanceof OPERATOR:

class A {
}

public class instance1 {
public static void main(String args[]) {
try {
Class cls = Class.forName("A");
boolean b1 = cls.isInstance(new Integer(37));
System.out.println(b1);
boolean b2 = cls.isInstance(new A());
System.out.println(b2);
} catch (Throwable e) {
System.err.println(e);
}
}
}

In this example, a Class Object of Class A is created, and then check whether some objects are instances of Class. INTEGER (37) is not, but new A () is.

3. Find out the Class Method

Find out what methods are defined in a class, which is a very valuable and basic reflection usage. The following code implements this usage:

import java.lang.reflect.*;

public class method1 {
private int f1(Object p, int x) throws NullPointerException {
if (p == null)
throw new NullPointerException();
return x;
}

public static void main(String args[]) {
try {
Class cls = Class.forName("method1");
Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
System.out.println("name = " + m.getName());
System.out.println("decl class = " + m.getDeclaringClass());
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("return type = " + m.getReturnType());
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}

This program first obtains the description of the Method1 class, and then calls getdeclaredmethods to obtain a series of methods.
Objects, which respectively describe each method defined in the class, including the public method, protected method, package method, and private
Method. If you use getmethods in the program to replace getdeclaredmethods, you can also obtain information about the inherited methods.

After obtaining the method object list, it is not difficult to display the parameter type, exception type, and return value type of these methods. Whether these types are basic or class types can be provided by the objects of the description class in order.

The output result is as follows:

name = f1

decl class = class method1

 param #0 class java.lang.Object

param #1 int

exc #0 class java.lang.NullPointerException

return type = int

-----
name = main

decl class = class method1

param #0 class [Ljava.lang.String;

return type = void

4. Get the constructor Information

The usage of the get class constructor is similar to that of the above method, for example:

import java.lang.reflect.*;

public class constructor1 {
public constructor1() {
}

protected constructor1(int i, double d) {
}

public static void main(String args[]) {
try {
Class cls = Class.forName("constructor1");
Constructor ctorlist[] = cls.getDeclaredConstructors();
for (int i = 0; i < ctorlist.length; i++) {
Constructor ct = ctorlist[i];
System.out.println("name = " + ct.getName());
System.out.println("decl class = " + ct.getDeclaringClass());
Class pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = ct.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}

In this example, information about the returned type is not obtained because the constructor does not return the type.

The result of this program running is:

Name = constructor1

Decl class = Class constructor1

-----
Name = constructor1

Decl class = Class constructor1

Param #0 int

Param #1 double





5. Obtain the fields (fields) of the class)

It is also possible to find out which data fields are defined in a class. The following code is doing this:

import java.lang.reflect.*;

public class field1 {
private double d;
public static final int i = 37;
String s = "testing";

 public static void main(String args[]) {
try {
Class cls = Class.forName("field1");
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}

This example is very similar to the previous one. In this example, we use a new modifier, which is also a reflection
Class, used to describe the modifier of field members, such as "Private int ". These modifiers are described by integers and use modifier. tostring
Returns the description of a string in the "official" order (for example, "static" before "final ). The output of this program is:

name = d

decl class = class field1

type = double

modifiers = private

-----
name = i

decl class = class field1

type = int

modifiers = public static final

-----
name = s

decl class = class field1

type = class java.lang.String

modifiers =

And obtain the method. When obtaining a field, you can only obtain the field information (getdeclaredfields) stated in the current class ), alternatively, you can obtain the fields defined in the parent class (getfields ).

6. Execute the method based on the method name.

The example is related to how to obtain class information. We can also use reflection to do other things, such as executing a method with a specified name. The following example demonstrates this operation:

import java.lang.reflect.*;
public class method2 {
public int add(int a, int b) {
return a + b;
}
public static void main(String args[]) {
try {
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, arglist);
Integer retval = (Integer) retobj;
System.out.println(retval.intValue());
} catch (Throwable e) {
System.err.println(e);
}
}
}

If a program knows that a method needs to be executed only when it is executed, the method name is specified during the running process of the Program (for example, javaBean development environment will do this), then the above program demonstrates how to do it.

In the preceding example, getmethod is used to find a method with two Integer Parameters named add. Find the method and create the corresponding method
After the object, execute it in the correct object instance. When executing this method, you need to provide a list of parameters. In the preceding example, two integers of integer 37 and 47 are respectively packaged.
Object. The execution method returns an integer object, which encapsulates the return value 84.

7. Create a new object

The constructor cannot be executed as the execution method, because executing a constructor means creating a new object (to be precise, the process of creating an object includes allocating memory and constructing an object ). Therefore, the most similar example is as follows:

import java.lang.reflect.*;

public class constructor2 {
public constructor2() {
}

public constructor2(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}

public static void main(String args[]) {
try {
Class cls = Class.forName("constructor2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Constructor ct = cls.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = ct.newInstance(arglist);
} catch (Throwable e) {
System.err.println(e);
}
}
}

Find the corresponding constructor Based on the specified parameter type and execute it to create a new object instance. This method can be used to dynamically create objects while the program is running, rather than creating objects during compilation, which is very valuable.

8. Change the field value.

Another use of reflection is to change the value of the object data field. Reflection: you can find and change the object field based on the name in a running program. The following example illustrates this point:

import java.lang.reflect.*;

public class field2 {
public double d;

public static void main(String args[]) {
try {
Class cls = Class.forName("field2");
Field fld = cls.getField("d");
field2 f2obj = new field2();
System.out.println("d = " + f2obj.d);
fld.setDouble(f2obj, 12.34);
System.out.println("d = " + f2obj.d);
} catch (Throwable e) {
System.err.println(e);
}
}
}

In this example, the field D value is changed to 12.34.

9. Use Arrays

The last usage of the reflection described in this article is the Operation Array created. Arrays are a special class type in Java. An array reference can be assigned to an object reference. Observe the following example to see how the array works:

import java.lang.reflect.*;

public class array1 {
public static void main(String args[]) {
try {
Class cls = Class.forName("java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String) Array.get(arr, 5);
System.out.println(s);
} catch (Throwable e) {
System.err.println(e);
}
}
}

In this example, a string array of 10 units of length is created, a value is assigned to the string at 5th locations, and the string is obtained and printed from the array.

The following code provides a more complex example:

import java.lang.reflect.*;

public class array2 {
public static void main(String args[]) {
int dims[] = new int[]{5, 10, 15};
Object arr = Array.newInstance(Integer.TYPE, dims);
Object arrobj = Array.get(arr, 3);
Class cls = arrobj.getClass().getComponentType();
System.out.println(cls);
arrobj = Array.get(arrobj, 5);
Array.setInt(arrobj, 10, 37);
int arrcast[][][] = (int[][][]) arr;
System.out.println(arrcast[3][5][10]);
}
}

In this example, an integer array of 5x10x15 is created, and a value is assigned to the element in [3] [5] [10 ].
37. Note that multi-dimensional arrays are actually arrays. For example, after the first array. Get, arrobj is a 10x15
. Then obtain an element, that is, an array with a length of 15, and assign a value to its 10th elements using array. setint.

Note that the type of the array is dynamic when it is created, and the type is unknown during compilation.

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.