Java Programming Idea (18)--Talk about reflection again

Source: Internet
Author: User
Tags object object

In the Java programming Idea (15)--The reflection of type information and the idea of Java programming (16)--Contact the JVM to talk about class, the book only use 3 pages to finish, and to talk about so many classes of things, the next to use from the reflection, the combination of API and other data to write more.


Example: Test.java

public class Test {public        test () {     } public    Test (int i) {   System.out.println (i);     } private void pri () {System.out.println ("private");} public void Pub () {System.out.println (' Public ');} protected void Pro () {System.out.println ("protected");} private string Pristr;public string pubstr;protected string Pro;}

There are different methods and domains.


Test:

Import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method ;p Ublic class Reflect {public static void main (string[] args) {try {//test parameter type followed by three-point action test t = new test (); T.three (); t.three ("A", "B", "C");//output [] [A,b,c] proves ... The argument can be either empty or a character array to be passed in English. varargs//the class object referencing Class C = class.forname ("test") that the test is loaded into the namespace to represent test;//method class gets the name Pu b The method of try {method one = C.getmethod ("Pub"); the try {//Method call Invoke (Object obj, object ... args) obj is the class to which the method is to be called Args is the parameter passed to the method//passed O BJ to be an instance, otherwise there will be object is not an instance of declaring Classone.invoke (C.newinstance ());} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch (InvocationTargetException e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ()}} catch (Nosuchmethodexception E1) {e1.printstacktrace ();} catch (SecurityException E1) {e1.printstacktrace ();} This method of returning an array of methods that are public methods including those inherited by the parent class and parent interface method[] method = C.getmeThods ();//Returns all the methods of the class declaration represented by the class object, including the public private protected method method[] Declaredmethod = C.getdeclaredmethods (); class[] array = c.getclasses (); field[] field = C.getfields ();  field[] Declaredfield = C.getdeclaredfields (); for (int i = 0; i < Array.Length; i++) {System.out.println ("Classes array Is "+array[i].getname ());} for (int i = 0; i < method.length; i++) {System.out.println ("Methods array is" +method[i].getname ());} Getreturntype gets the property returned by the method. for (int i = 0; i < declaredmethod.length; i++) {System.out.println ("Declaredmethods array is" +declaredmethod[i].getre Turntype (). GetName () + "" "+declaredmethod[i].getname ()); try {try {String s[] ={" 1 "," 2 "};//If not set there will be class Reflect can not Access a member of Class Test with//modifiers "Private" Exception//constructor, Field, Method for AccessibleObject subclass//Permissions with access control default is false to force Java to make access checks, so private is forbidden to access the filed empathy declaredmethod[i].setaccessible (true); System.out.println (Declaredmethod[i].getname ()); if (Declaredmethod[i].getname (). Equals ("three") {System.out.println ("true");//The following article will be reported wrong number of arguments exception//This problem is the oldest thing in my Chinese is all the nonsense of the previous article//invoke (Object obj, Object ... args) array is covariant string[] is considered as the entire parameter and the element inside the String array is not the first parameter of the args (not the object[]//string[), in fact, Our string array is the first element of the OBJEC array */* This is because the compiler will pass the string array as a variable length parameter to the object o, and we get the method with only one argument, so there will be wrong number ofarguments exception, All we have to do is cast the string array to a single Object object to resolve the exception. This is bullshit. *///declaredmethod[i].invoke (C.newinstance (), s);d Eclaredmethod[i]. Invoke (C.newinstance (), New Object[]{s});d Eclaredmethod[i].invoke (C.newinstance (), (Object) New string[]{"1", "2", "3 "});d Eclaredmethod[i].invoke (C.newinstance (), (object) null);d Eclaredmethod[i].invoke (C.newinstance (), (object) New string[]{});} Else{declaredmethod[i].invoke (C.newinstance ());}} catch (Instantiationexception e) {e.printstacktrace ();}} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch (InvocationTargetException e) {e.printstacktrace ();}} In the same vein as method, only filed get the domain. for (int i = 0; i < Field.length; i++) {System.out.println ("fields array is" +field[i].getname ());} for (int i = 0; i < declaredfield.length; i++) {System.out.println ("declaredfieds array is" +declaredfield[i].getname () try {declaredfield[i].setaccessible (true);d Eclaredfield[i].set (T, "a");} catch (IllegalArgumentException e) { E.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();}} System.out.println (T.pro); System.out.println (t.pub);} catch (ClassNotFoundException e) {e.printstacktrace ();}}}

Basic all the problem and attribute method are inside, but wrong number of arguments exception, is I checked the most long exception, calm down after the heart to see understand.

This is because the compiler passes the string array as a variable-length parameter to the object o, and we get the method with only one argument,
So there's an exception to the wrong number of arguments, and we'll just have to cast the string array to an object to resolve the exception.


All of this is the wrong answer, invoke (Object obj, Object ... args), array is covariant string[] is treated as object[].

String[] is treated as the entire parameter, and the element inside the string array is not an object.
Instead of the first parameter of args, in fact, our string array is the first element of the OBJEC array.


Take a slow look and you understand.


Added later:

constructor<?>[] ct = class.forname ("Test"). GetConstructors (); for (int i = 0; i < ct.length; i++) {System.out.pri Ntln ("Constructor:" + ct[i].getname ());} System.out.println ("new instance"), try {ct[0].newinstance (); ct[1].newinstance (123);} catch (Instantiationexception | illegalaccessexception| IllegalArgumentException | InvocationTargetException E2) {e2.printstacktrace ();}

constructor is the constructor, but unlike class's Newinstace method, constructor's newinstance (Object ... initargs) is varargs, which is the three point mentioned above. Parameters can be passed in.

The interesting point is that the constructor array is ordered, as long as your constructor is written in front of the class, and if there are other methods before it, then the order of the arrays is not sorted by rank.


The function of reflection is to check the type of object at run time, any method that calls the object (spring and servlet are used, note that we are in the XML configuration, and then the property is injected according to XML), and we can know the method parameters and properties.


Although this is to break the so-called encapsulation, private property, but think, there is no backdoor, language is not dead?

For reflection, want to know more than can see foreign reflection tutorial, http://www.programcreek.com/2013/09/java-reflection-tutorial/

Java Programming Idea (18)--Talk about reflection 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.