Java Programming Idea (15)--reflection of type information

Source: Internet
Author: User

After the Class,class, continue.


1) Generalization of class reference

Class can also be added to generics, and type checking is done after joining.


Post the book with the exact words,class<?> better than class, although they are equivalent to the,class<?> benefit is the coincidence or negligence of using a non-specific class reference. I don't know what this is, what's a non-specific?

Understand the back, in fact, <?> as a wildcard, is unknown, directly write the conclusion can not write a specific type bar, the author of the meaning is actually said to add a generic class is the choice of non-specific version.


The reason for joining generics is to provide a type check during compilation, and the error will be displayed if the operation is wrong, but when using the normal class, it is time to wait until it is run.


And in this CLASS<T>,JDK document:

-the type of the
T class modeled by this Class object. For example, the type of String.class is Class<String> . Use Class<?> if the class being modeled is unknown.
<T> is a declaration that uses a generic class. Include:Interface list<e>
    • Type Parameters:
      E-The type of elements in this list

The same is the statement.


2) Transformation Grammar

SE5 added syntax for class reference transformation.

class gun{int price = 1;} Class Deathgun extends gun{int price = 2;}        public class Testcast {public static void main (string[] args) {Gun g = new Deathgun ();        class<deathgun> d = deathgun.class;          The generic type of usefulness does not match//class<deathgun> dd = gun.class;        Deathgun GG = D.cast (g);    System.out.println (Gg.price); }}cast Source: Public T cast (Object obj) {    if (obj! = null &&!isinstance (obj))       throw new ClassCastException (ca Nnotcastmsg (obj));    Return (T) obj;

3) Check before type conversion

if (x instanceof TV) {  (TV) x). Show ();}

Check the object type, and if there is an error when transitioning down, throw classcastexception, so use instanceof first.


The equivalence between instaceof and class.

Class Father{}class Son extends Father{}public class Test {static void Test (Object o) {System.out.println ("Ty        PE: "+o.getclass ());        System.out.println ("O instanceof Father:" + (o instanceof Father));        System.out.println ("O instanceof son:" + (o instanceof son));        System.out.println ("father.isinstanceof (o)" +father.class.isinstance (o));        System.out.println ("son.isinstanceof (o)" +son.class.isinstance (o));        System.out.println ("O.getclass () ==father.class:" + (O.getclass () ==father.class));        System.out.println ("O.getclass () ==son.class:" + (O.getclass () ==son.class));        System.out.println ("O.getclass (). Equals (Father.class):" + (O.getclass (). Equals (Father.class)));    System.out.println ("O.getclass (). Equals (Son.class):" + (O.getclass (). Equals (Son.class)));        } public static void Main (string[] args) {Test (New Father ());    Test (New Son ()); }}result:type:class son. Fathero instanceof Father:trueo instanceof Son:falseFather.isInStanceof (o) trueson.isinstanceof (o) falseo.getclass () ==father.class:trueo.getclass () ==son.class:falseo.getclass ( ). Equals (Father.class): Trueo.getclass (). Equals (Son.class): Falsetype:class Son. Sono instanceof father:trueo instanceof Son:trueFather.isInstanceOf (o) trueson.isinstanceof (o) trueo.getclass () = = Father.class:falseo.getClass () ==son.class:trueo.getclass (). Equals (Father.class): Falseo.getclass (). Equals ( Son.class): True

Instanceof refers to you are this class? Are you a derived class of this class?


4) Reflection

The book is very simple, about 3 pages.

RTTI, run-time type information can tell you the exact type of object, but this type must be known at compile time so that RTTI can be recognized. That is, at compile time, the compiler must know the class to be processed by Rtti.

This does not seem to be a limitation, but in large-scale programming, it is possible for a compile-time program not to know the class the object belongs to.

The real difference between RTTI and reflection is only: RTTI, the compiler checks and opens the. class file at compile time, for reflection, the. class file is not available at compile time and is opened and checked at run time. class file.


Directly with the example in the book, Put a code:

public class Showmethods {  private static String usage =    "usage:\n" +    "Showmeth ODS qualified.class.name\n "+   " to show all methods in class or:\n "+   " Showmethods qual Ified.class.name word\n "+   " to search for methods involving ' word ' ";  private static Pattern p = Pa Ttern.compile ("\\w+\\.");   public static void main (string[] args) {    if (Args.length < 1) {      System.out.println (usage);      system.exit (0);   }    int lines = 0;    try {      class<?> c = class.forname (Args[0]);  & nbsp;    method[] methods = C.getmethods ();      constructor[] Ctors = C.getconstructors ();      if (args.length = = 1) {         for (Method method:methods)           System.out.println (             P.matcher (Method.tostring ()). ReplaceAll (""));         for (Constructor ctor:ctors)           System.out.println ( P.matcher (Ctor.tostring ()). ReplaceAll (""));        lines = Methods.length + ctors.length;     } else {//actually the author writes that the method match will match if I Java showmethods showmethods showmethods//original words is to extract one of them, but args[1] for showmethods, just good match to the showmethods itself is the method, that is, the main method.         for (Method method:methods)            if (method.tostring (). IndexOf (args[1])!! =-1) {             System.out.println (              P.matcher (Method.tostring ()). RePlaceall (""));            lines++;          }        for (Constructor ctor:ctors)           if (ctor.tostring (). IndexOf (args[1])!! =-1) {             System.out.println (P.matcher (               ctor.tostring ()). ReplaceAll (""));             lines++;          }     }   } catch (ClassNotFoundException e) {       SYSTEM.OUT.PRINTLN ("No such class:" + E);   } }} F:\>java showmethods showmethodspublic s tatic void Main (string[]) public final native Class GetClass () public native int hashcode () public boolean equals (Object) public String toString () public final native void notify () public final native void Notifyall () public final native void Wait (long) throws interruptedexceptionpublic final void Wait (Long,int) throws interruptedexceptionpublic final void wait () throws Interruptedexceptionpublic Showmethods ()

Take a slow look at Matcher's ReplaceAll method, which differs from string ReplaceAll, which has two parameters, a replacement, and a content to be replaced. And the former has only one parameter.

public string ReplaceAll (string replacement)
Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
public class TestString {public      static void Main (string[] args) {          String s = "0898" ((* (*)) (";        The regular expression is compiled into       the pattern pattern p = pattern.compile ("\\w");        P.matcher returns the Matcher object, the ReplaceAll method of Matcher is to replace the matched string        //with the contents of the method parameter.       System.out.println (P.matcher (s). ReplaceAll ("-"));    }  }  result:0898--------
If there is no replacement for the regular expression, the result is:

public static void Showmethods.main (java.lang.string[]) public final native Java.lang.Class Java.lang.Object.getClass ( public native int Java.lang.Object.hashCode () public boolean java.lang.Object.equals (java.lang.Object) public Java.lang.String java.lang.Object.toString () public final native void Java.lang.Object.notify () public final native void JAVA.LANG.OBJECT.NOTIFYALL () Public final native void Java.lang.Object.wait (long) throws Java.lang.InterruptedExceptionpublic final void java.lang.Object.wait (Long,int) throws Java.lang.InterruptedExceptionpublic final void Java.lang.Object.wait () throws Java.lang.InterruptedExceptionpublic Showmethods ()
It 's actually replacing the package name in front of the class.

It has not been found that the results of forname are not known at compile time, we are in the runtime to pass into the class parameters. Although at first it was useless to such a high level of things, but after learning deep in the later found something in use, such as spring.


GetMethods gets all the common methods of the class, including itself, inherited from the parent class, and the public method implemented from the interface.

Another is that Getdeclaredmethods got the method of declaring the class itself, more than the public method, protected can also get, even private. ( at first I was also very confused, not often stressed encapsulation, private not let others see, how can directly get the private things, in fact, can see, what has a degree, but this degree is not a dust not broken, there is a certain back door ).


GetConstructors returns the constructor for public. For a try, the private constructor is not displayed. The book says it stops and continues to expand:

I have seen the Java Reflection Tutorial in the past is very good introduction.


One, unknown method call

public class Testrefl {public    static void Main (string[] args) {        UnKnown UK = new UnKnown ();        Method m = null;        try {            m = Uk.getclass (). GetMethod ("Print", new class<?>[0]);                M.invoke (UK);        } catch (Nosuchmethodexception | invocationtargetexception| SecurityException  | Illegalaccessexception e) {            e.printstacktrace ();}}    } Class unknown{public    void print () {        System.out.println ("haha");}    }
I specifically changed the method to private, found that the method can not find, only to public.


Ii. Creation of objects

public class Testrefl {public    static void Main (string[] args) {       class c = null;       try {        c = c.forname ("son. UnKnown ");        System.out.println (C.getname ());    } catch (ClassNotFoundException e) {        System.out.println ("not Found");    }       try {        UnKnown u = (UnKnown) c.newinstance ();        U.print ();    } catch (Instantiationexception e) {        e.printstacktrace ();    } catch (Illegalaccessexception e) {        E.printstacktrace ();}}}    Class unknown{   static  void print () {        System.out.println ("haha");}    }

Gets the object through the constructor.

public class Testrefl {public static void main (string[] args) {class c = null; try {c = c.forname ("son.        UnKnown ");        } catch (ClassNotFoundException e) {System.out.println ("not Found");        } constructor<?> ct[] = c.getconstructors ();            try {UnKnown u = (UnKnown) ct[0].newinstance ();            UnKnown U2 = (UnKnown) ct[1].newinstance (1);            U.print ();        U2.print ();        } catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();         } catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace (); }}}class UnKnown {public UNknown () {} public UnKnown (int i) {} static void print () {System.out.println ("haha"); }}
The constructor array is in order, 0 is the parameterless constructor, and 1 is the parameter, which can be passed directly in the method. Of course, the private construction method is not to be taken.


Explaining the difference between Rtti and reflection, which in turn illustrates the effect of reflection, is that the runtime examines the object's type, arbitrarily invoking the object's methods (both spring and servlet are used, notice that we are in the XML configuration, and then the attributes are injected according to XML), You can also know the method parameters and properties.


The reflection is still very powerful, and the next step is to introduce the dynamic agent, a design pattern that has been abused before.

Java Programming Idea (15)--reflection of type information

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.