In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this "case analysis of Java reflection mechanism" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "case analysis of Java reflection mechanism" article.
Java reflection mechanism
The reflection mechanism of Java means that in the running state of the program, the object of any class can be constructed, the class to which any object belongs, the member variables and methods of any class can be understood, and the properties and methods of any object can be called. This function of dynamically obtaining program information and dynamically calling objects is called the reflection mechanism of Java language. Reflection is seen as the key to dynamic languages.
I'm not very good at words, so let's just do the picture above.
An example of not using a reflection mechanism
/ / define an animals interface interface animals {public abstract void print ();} / define a class to implement the abstract method class Dog implements animals {public void print () {System.out.println ("Dog");}} class Cat implements animals {public void print () {System.out.println ("Cat") of the animals interface. }} / / construct a zoo class / / later if we only need to modify the zoo class class zoo {public static animals getInstance (String animalsName) {animals a = null; if ("Dog" .equals (animalsName)) {a = new Dog ();} if ("Cat" .equals (animalsName)) {a = new Cat () } return a;}} public class reflection {public static void main (String [] args) {/ / find the corresponding class to implement the interface animals a=zoo.getInstance ("Cat") with the help of the zoo class; if (ajar null) a.print ();}}
At this time, all you need to add animals is
Add CLA
Modify zoo
Modify the animal class of the main function
Change the above to the reflection mechanism
/ / define an animals interface interface animals {public abstract void print ();} / define a class to implement the abstract method class Dog implements animals {public void print () {System.out.println ("Dog");}} class Cat implements animals {public void print () {System.out.println ("Cat") of the animals interface. }} / / construct a zoo class / / later if we only need to modify the zoo class class zoo {public static animals getInstance (String className) {animals a = null; try {/ / find the class name with Class.forName and instantiate with newInstance similar to new a = (animals) Class.forName (className). NewInstance () } catch (Exception e) {e.printStackTrace ();} return a;}} public class reflection {public static void main (String [] args) {/ / find the corresponding class with the help of zoo class to implement the interface (classname is the current package name plus class name) animals a = zoo.getInstance ("com.cc1.Dog") If (a! = null) a.print ();}}
At this time, all you need to add animals is
Add CLA
Modify the animal class of the main function
Saving one step, passing in the class name is controllable, and it seems that all the existing classes can be adjusted.
Reflection mechanism method
What we use most is probably
ForName (calling class)
GetMethod (calling methods under the class)
Invoke (execution)
NewInstance (instantiated object)
Class.forName (className) .getMethod (methodName) .invoke (Class.forName (className) .newInstance ())
Let's use the reflection mechanism to pop up the computer (calc) or notepad (notepad).
Because the computer pops up a little too much, I'll play notepad this time. All in all, it's wonderful to be able to pop up.
Runtime.getRuntime () .exec (notepad)
Let's take a look at the getRuntime function
I know that this function is the way that the Runtime class gets the object. I feel that it is troublesome to call it every time I use it, so it is encapsulated into a function in order not to call one object at a time.
How to get class objects
Class.forName (class name acquisition)
Zoo.class (classes that have been loaded)
Obj.class (instance)
Class initialization
Modify the zoo class to add initial blocks, static initial blocks, and constructors
Class zoo {/ / initial block {System.out.println ("1" + this.getClass ());} / / static initial block static {System.out.println ("2" + zoo.class);} public zoo () {System.out.println ("3" + this.getClass ());} public static animals getInstance (String className) {animals a = null Try {/ / looks for the class name with Class.forName and instantiates with newInstance similar to new a = (animals) Class.forName (className). NewInstance ();} catch (Exception e) {e.printStackTrace ();} return a;}}
Class initialization execution order: static initial block
Class instantiation execution order: static initial block-> initial block-> constructor
From this, we know that class initialization and class instantiation are different.
Next, add the zoo1 class to inherit the zoo class
Class zoo1 extends zoo {/ / initial block {System.out.println ("11" + this.getClass ());} / / static initial block static {System.out.println ("12" + zoo.class);} public zoo1 () {System.out.println ("13" + this.getClass ());}}
Subclass initialization order: parent static initialization block-> subclass static initialization block
Subclass instantiation order: parent static initialization block-> subclass static initialization block-> parent initialization block-> parent class constructor-> subclass initialization block-> subclass constructor
As can be seen above, when using Class.forName, and the class static initialization block is controllable, arbitrary code can be executed.
Call inner class
Class.forName ("java.lang.Runtime") to get the class (java.lang.Runtime is the full path of the Runtime class)
GetMethod
The role of getMethod is to obtain a specific public method of a class through reflection.
Java supports class overloading, but you cannot determine a function only by a function name, so when you call getMethod, you need to pass a list of parameter types to its method
Class.forName ("java.lang.Runtime") .getMethod ("exec", String.class)
Invoke
The difference between static and dynamic methods
The invoke method passes parameters when acting under the getMethod class and executes the method.
Public Object invoke (Object obj, Object... Args)
The first parameter is the class object of the method obtained by getMethod (pass the class if the method is static)
Get the class object of the exec function
Class.forName ("java.lang.Runtime") .getMethod ("getRuntime") .invoke (Class.forName ("java.lang.Runtime"))
Because getRuntime is a static method, pass the class
Invoke (Class.forName ("java.lang.Runtime") .getMethod ("getRuntime") .invoke (Class.forName ("java.lang.Runtime")), "calc.exe")
Finally, let's merge.
Class.forName ("java.lang.Runtime"). GetMethod ("exec", String.class). Invoke (Class.forName ("java.lang.Runtime") .getMethod ("getRuntime") .invoke (Class.forName ("java.lang.Runtime")), "notepad")
Specify the construction method to generate the instance String str= "notepad"; ProcessBuilder pb = new ProcessBuilder (str); pb.start ()
GetConsturctor (the function can select a constructor in the specified interface format (because the constructor can also be overloaded based on parameters)
Once selected, we can execute the constructor through newInstance () and passing in the parameters of the constructor
The ProcessBuilder class has two constructors
Public ProcessBuilder (String... Command) (String … Variable length string array String [] .class)
Public ProcessBuilder (List command)
Use construction methods separately
Class.forName ("java.lang.ProcessBuilder") .getConstructor (String [] .class) .newInstance (new String [] [] {
{"notepad"}})
Class.forName ("java.lang.ProcessBuilder") .getConstructor (List.class) .newInstance (Arrays.asList ("notepad"))
After executing the constructor instance, you can use the start function after the forced conversion
((ProcessBuilder) Class.forName ("java.lang.ProcessBuilder") .getConstructor (List.class) .newInstance (Arrays.asList ("notepad")) .start ()
In practice, it certainly can't be used. How can there be such a good thing? let's just keep reflecting.
Class.forName ("java.lang.ProcessBuilder") .getMethod ("start") .invoke (clazz.getConstructor (List.class) .newInstance (Arrays.asList ("notepad")
Some people here may be curious about another constructor I wrote in Rina, String. Why does the parameter command use new String [] [] {{"notepad"}}? it should not be new String [] {"notepad"}. It should be used now.
((ProcessBuilder) Class.forName ("java.lang.ProcessBuilder") .getConstructor (String [] .class) .newInstance (new String [] {"notepad"})) .start ()
Debug at the break point in this line
What we are passing is a string array that becomes a string when instantiated, and then look at another constructor (List).
((ProcessBuilder) Class.forName ("java.lang.ProcessBuilder") .getConstructor (List.class) .newInstance (Arrays.asList ("notepad")) .start ()
It's still the breaking point in this business.
It can be seen that when List is passed in, it will be treated as the first item of Object, and String [] will be treated as Object, so add an extra layer [] {}
Execute private methods
Get private methods through the function getDeclaredConstructor, and then use setAccessible (true) to break private method restrictions.
Class cls = Class.forName ("java.lang.Runtime"); Constructor m = cls.getDeclaredConstructor (); m.setAccessible (true); cls.getMethod ("exec", String.class) .invoke (m.newInstance (), "notepad") The above is about the content of this article "case Analysis of Java reflection Mechanism". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.