Introduction
First, let me introduce some less practical explanations: the JAVA reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any methods and properties of it; this function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language.
Simple use
Reflection is a very common and easy-to-use way in Java (but you need to know that its efficiency is relatively low, so you should use it with caution) Of course, it can also be used in Android based on the Java language. We can use reflection to obtain some classes that are not open but existential, so as to call some of its methods. Let's briefly write it down below, using java reflection to obtain classes and the implementation of methods that call it.
//The path of the class that needs to be called reflect String className = "com.example.test.JavaReflect";Class reflect = null;try { //Get java class reflect = Class.forName(className); //Instantiate the corresponding class Object javaReflect = reflect.newInstance(); if(null != javaReflect) { //Reflect the stringToUp() method in the Class class stringToUp is the method name, and String.class is the parameter type Method stringToUp = reflect.getDeclaredMethod("stringToUp", String.class); //Cancel the legality check of accessing private methods stringToUp.setAccessible(true); //Calculate the stringToUp() method, the first parameter represents the corresponding class, and the second is the parameter of the method String str = (String) stringToUp.invoke(javaReflect,"java reflect test"); System.out.println("result:"+str); }}catch (Exception e) { e.printStackTrace();} Let's take a look at what I did in stringToUp:
public String stringToUp(String str){ return str.toUpperCase();}In fact, it is just a string to convert it into capital, and then return it. OK, let's take a look at the output result:
01-02 08:09:11.959 6150-6150/com.zxf.alpha I/System.out: result:JAVA REFLECT TEST
It's simply perfect.
Summarize
OK, the above is all about this article. Reflection has many applications in Android. For example, when our project has multiple modules, you can do this if you want to call a method of the main program in the module, or you can use reflection to call some system-public methods, but the efficiency is not very high. I hope the content of this article will be helpful to everyone to learn or use radiation in Java. If you have any questions, you can leave a message to communicate.