Java reflection note

Source: Internet
Author: User

This article uses Java reflection

Experience summary can also be said to be some tips. In the future, new tips will be learned and updated constantly. I am not going to discuss the Java reflection mechanism in this article. There are a lot of reflection mechanisms on the Internet. You can simply Google them.

Before starting, define a test class student. The Code is as follows:

1 package CHB. Test. Reflect;
2
3 Public class student {
4 private int age;
5 private string name;
6 Public int getage (){
7 return age;
8}
9 Public void setage (INT age ){
10 This. Age = age;
11}
12 Public String getname (){
13 return name;
14}
15 public void setname (string name ){
16 this. Name = Name;
17}
18
19 public static void HI (INT age, string name ){
20 system. Out. println ("Hello everyone, my name is" + name + ", this year" + age + "years old ");
21}
22}

1. General steps for using Java reflection

Reflection calls are generally divided into three steps:

  • Get the class to be called
  • Obtain the method in the class to be called)
  • Method call (invoke)

Sample Code:

1 Class cls = Class.forName("chb.test.reflect.Student");   
2 Method m = cls.getDeclaredMethod("hi",new Class[]{int.class,String.class});
3 m.invoke(cls.newInstance(),20,"chb");

Ii. parameter types in method calls

In method calling, the parameter type must be correct. Note that you cannot replace the basic type with the packaging class. For example, you cannot replace Int. Class with integer. Class.

If I want to call the setage method of student, the following call is correct.

1 Class cls = Class.forName("chb.test.reflect.Student");   
2 Method setMethod = cls.getDeclaredMethod("setAge",int.class);
3 setMethod.invoke(cls.newInstance(), 15);

If we replace Int. Class with integer. Class, an error occurs, for example:

1 Class cls = Class.forName("chb.test.reflect.Student");   
2 Method setMethod = cls.getDeclaredMethod("setAge",Integer.class);
3 setMethod.invoke(cls.newInstance(), 15);

JVM reports the following exception:

1 java.lang.NoSuchMethodException: chb.test.reflect.Student.setAge(java.lang.Integer)   
2 at java.lang.Class.getDeclaredMethod(Unknown Source)
3 at chb.test.reflect.TestClass.testReflect(TestClass.java:23)

Iii. Reflection call of static methods

When calling the static method, you do not need to get an object example, as shown below:

1 class CLS = Class. forname ("CHB. Test. Reflect. Student ");
2 method staticmethod = Cls. getdeclaredmethod ("hi", Int. Class, String. Class );
3 staticmethod. Invoke (CLS, 20, "CHB"); // newinstance is not required here
4 // staticmethod. Invoke (CLS. newinstance (), 20, "CHB ");

Iv. assign values to private member variables

It is not allowed to assign values directly to the private member variable of the class through reflection. In this case, we can use the setaccessible method. Sample Code:

1 class CLS = Class. forname ("CHB. Test. Reflect. Student ");
2 object student = Cls. newinstance (); // get an instance
3 field = Cls. getdeclaredfield ("Age ");
4 field. Set (student, 10 );
5 system. Out. println (field. Get (student ));

When you run the code above, the system reports the following exception:

1 java.lang.IllegalAccessException: Class chb.test.reflect.TestClass can not access a member of class chb.test.reflect.Student with modifiers "private"   
2 at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
3 at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
4 at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
5 at java.lang.reflect.Field.set(Unknown Source)
6 at chb.test.reflect.TestClass.testReflect(TestClass.java:20)

Solution:

1 class CLS = Class. forname ("CHB. Test. Reflect. Student ");
2 object student = Cls. newinstance ();
3 field = Cls. getdeclaredfield ("Age ");
4 field. setaccessible (true); // you can specify whether to allow access.
5 field. Set (student, 10 );
6 system. Out. println (field. Get (student ));

In fact, in some cases (the classes include get and set methods), you can first call the set method and then call the get method to achieve the above effect. The code example is as follows:

1 class CLS = Class. forname ("CHB. Test. Reflect. Student ");
2 object student = Cls. newinstance ();
3
4 method setmethod = Cls. getdeclaredmethod ("setage", integer. Class );
5 setmethod. Invoke (student, 15); // call the Set Method
6
7 method getmethod = Cls. getdeclaredmethod ("getage ");
8 system. Out. println (getmethod. Invoke (student); // call the get method again.

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.