Java reflection--using the detailed

Source: Internet
Author: User
Tags array length modifiers idf

There are many interpretations of Java reflection on the Internet, and many official languages are not well understood.

What I'm talking about here is that therole of Java reflection is to deserialize the class from the Java virtual machine to get an example of that.

Then it is more useful, such as the intent object that the Startyactivity () method in Android has passed in. What is actually used in the interior is the reflection of Java.

First, write a test class Reflectbean

/** * Reflective entity class * / Public  class Reflectbean implements ireflect {    @RetentionTest(Hello ="Hai", World ="SB")Private intIdPrivateString[] names;PrivateArraylist<double> doubles; Public int getId() {returnId } Public void setId(intID) { This. id = ID; }@Override     Public void OnButtonClick(View v) {    }@Override     Public void Oncheckclick() {    } Public enumReflectenum {One, TOW, three; } Public Reflectbean() {    } Public Reflectbean(String AAA) {    } Public Reflectbean(string[] AAA) {    } Public void reflectetest() {    }@RetentionTest(World ="Hahahhaa") PublicStringReflectadd(String AAA) {LOG.I ("Test","Reflectadd method call:"+ AAA);returnaaa }}
/** * 测试接口 */publicinterface IReflect {    void onButtonClick(View v);    void onCheckClick();}

Good. Let me tell you about the use of Java reflection.

The Prime Minister defines a Reflectmobel class

1, three ways to reflect a class

privatestaticfinal"com.android.ui.reflect.ReflectBean";             /**             * 反射一个类有三种方法             * */            //1            Class<ReflectBean> class1 = ReflectBean.class;            Log.i("test", class1.getName());            //2            Class class2 = Class.forName(className);            //3            new ReflectBean();            Class class3 = reflectBean1.getClass();

2, Get class loader

Log.i("test""类加载器  " + class1.getClass().getClassLoader().getClass().getName());

In fact, there are three kinds of class loaders in Java.

1,bootstrap ClassLoader This loader is written in C + + and is rare in general development.
The 2,extension ClassLoader is used to load the extended class, which typically corresponds to classes in the Jre\lib\ext directory.
3,appclassloader loads the classpath specified class, which is the most commonly used loader. It is also the default loader in Java.

3, get the Java object corresponding to class

            /**             * 获取对象             * 调用了ReflectMobel的无参数构造方法.即对象             * */            object = class1.newInstance();            ReflectBean reflectBean = class1.newInstance();            ifreturn;//判断某个实例是否属于这个类

4. Get the method object in class

/**             * 获得类中的一个方法             */            //有参数            Method method = class1.getDeclaredMethod("reflectAdd", String.class);            //无参数            Method method1 = class1.getDeclaredMethod("reflecteTest");            //多个参数            Method method2 = class1.getDeclaredMethod("reflecteTest"new Class[]{String.class,int.class});            Log.i("test""reflectAdd方法:" + method.getName() + method1.getName());

5. Get annotations for class tags

if (method.isAnnotationPresent(RetentionTest.class)) {//判断该类有没有标记这个注解                RetentionTest retentionTest = method.getAnnotation(RetentionTest.class);                Log.i("test", "reflectAdd标记的注解:" + retentionTest.world());            }

6, calling method

            /**             * 调用该方法             * 如果该方法没有参数,则传入new Object[]{}             * 如果该方法有参数,则传入参数             * 返回结果为该方法的返回结果             * */            "bbbbbb");            Log.i("test""reflectAdd方法的返回结果:" + aaa);            method1.invoke(reflectBean);//无参方法            new Object[]{});//无参方法

7. Get information about a class

//Modifier for class            StringClassxiushifu=Modifier.ToString (Class1.GetModifiers ());Log.I"Test","Modifier for class:" +CLASSXIUSHIFU);//A simple name for a class that refers to a name without a package path            StringClasssimplename=Class1.Getsimplename ();Log.I"Test","The simple name of the class, which means the name without the package path:" +Classsimplename);//class with the name of the package path            StringClassName=Class1.GetName ();Log.I"Test","The name of the class with the package path:" +ClassName);

8, get all the constructors

//Get all the constructorsconstructor<?> cons[] = class1.getconstructors (); Constructor Constructor = Class1.getconstructor ();//No parameter constructorConstructor Constructor1 = Class1.getconstructor (String.class);//constructor with string parameterConstructor Constructor2 = Class1.getconstructor (NewClass[]{string.class,Double.class});//constructor with string parameterLOG.I ("Test","Constructor for class:"+ Constructor1.getname ()); for(inti =0; i < cons.length; i++) {LOG.I ("Test","Constructor for class:"+ Cons[i].getname ()); }

9, gets all the interfaces in the class

//保存所有的接口            Class<?> intes[] = class1.getInterfaces();            for (int0; i < intes.length; i++) {                Log.i("test""类的接口:" + intes[i].getName());            }

10, gets the parent class of the current class

//取得父类            Class<?> temp = class1.getSuperclass();

11, get the properties in the class, get all the properties

 /** * Get Properties            * Divided into all attributes and specified properties * 1, get all properties * */ //get all Properties             field[] fields = Class1.getdeclaredfields (); for  (Field field:fields) {log.i ( "test" ,  "Get property modifiers:"  + modifier.to String (Field.getmodifiers ()));                //get modifiers for properties, such as public,static and so on  LOG.I ( "test" ,  "property of type name:"  + Field.gettype (). Getsimplename ());                //property  LOG.I ( "test" ,  "property Name:"  + field.getname ()); //property name }  

12, gets the property in the class, gets the specified property

/** * 2, get specific Properties * * /Field IdF = Class1. Getdeclaredfield("id");Idf. Setaccessible(true);//Use the reflection mechanism to break the encapsulation and cause the properties of the Java object to be unsafe. Setting AccessibilityIdf. Set(Reflectbean,111);Log. I("Test","Property's name:"+ IdF. GetName()); The value of the//idLog. I("Test",The value of the property:+ IdF. Get(Reflectbean). toString());//string valueField STRINGSF = Class1. Getdeclaredfield("Names");Stringsf. Setaccessible(true);//Use the reflection mechanism to break the encapsulation and cause the properties of the Java object to be unsafe. Setting AccessibilityStringsf. Set(Reflectbean, New string[]{"AAA","BBB","CCC"});String[] AAAS = (string[]) stringsf. Get(Reflectbean);Log. I("Test","Property's name:"+ STRINGSF. GetName());//string valueLog. I("Test",The value of the property:+ aaas[0]);//string valueLog. I("Test",The value of the property:+ Array. Get(AAAS,1));//string valueLog. I("Test","Array Length"+ Array. GetLength(AAAS));Log. I("Test","The first element of the array:"+ Array. Get(AAAS,0));

Precautions :
When we use the constructor to obtain the class construction method, the following:

//2、根据构造器参数类型获取相应的构造器对象               Constructor csr = cls.getConstructor(String[].class);          //3、创建实体对象           ObjectString[]{}

If you need to pass in the constructor method and pass in only one array, an error will be reached.

So what is the reason for the mistake?
Because the class constructor method (String strs[]) has only one parameter of a string array so this is the compiler will pass the string array as a variable length parameter to the object STRs, and we get the method has only one parameter, so it will appear wrong number of Arguments, we can resolve this exception simply by casting the string array to an object.

The correct wording is:

//2、根据构造器参数类型获取相应的构造器对象               Constructor csr = cls.getConstructor(String[].class);           String str[]={"111","123"};           //3、创建实体对象           Student entity = (Student)csr.newInstance((Object)str);  

There's one more detail to note.

//with Parameters             method  = Class1. Getdeclaredmethod ("Reflectadd", String.  Class);            //No parameters             Method method1 = Class1. Getdeclaredmethod ("Reflectetest");            //Multiple parameters             Method method2 = Class1. Getdeclaredmethod ("Reflectetest", new Class[]{string.  Class, int.class});String AAA = (string) method. Invoke (Reflectbean, "bbbbbb");

When we need to invoke a method in a class, invoke to invoke the method call is only public, if the private type is called an error.

The common method of Java reflection is to make these. We can do a lot of things according to the characteristics of reflection. Working with annotations, for example, can make your program more flexible.

The actual usage scenarios for Java reflection also need to be based on your own program usage.

Java reflection--using the detailed

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.