Java Reflection Mechanism Example

Source: Internet
Author: User

Link:

Http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

 Packagecom.stono.reftest;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier; Public classRef {@SuppressWarnings ("Unused")     Public Static voidMain (string[] args)throwsException {//instantiate a class object;Glyph Glyph =NewGlyph (); Class<?extendsglyph> Class1 =Glyph.getclass (); Class<?> Class2 = Glyph.class; Class<?>CLASS3; CLASS3= Class.forName ("Com.stono.reftest.Glyph"); //classes are instantiated through class objects, and there must be no parameter constructorsGlyph GLYPH2 =class1.newinstance (); //get the constructor function through the class object;Constructor<?>[] Constructors = class1.getconstructors ();//Length of 1//gets the modifier of the constructor        intmodifiers = Constructors[0].getmodifiers (); //gets the modifier string;String Modifierstr =modifier.tostring (modifiers); //gets the parameter type of the constructor;class<?>[] Parametertypes = constructors[0].getparametertypes (); //Constructs the object through the constructor function;Glyph Glyph3 = (Glyph) constructors[0].newinstance (); //gets all the interfaces of the class;Class<?>[] Interfaces =class3.getinterfaces (); //gets the parent class of the classClass<?> superclass =Class3.getsuperclass (); //gets all the methods of the class and does not return a constructor;Method[] Methods =Class3.getmethods (); //gets the exception type; constructor and method are inherited from AccessibleObjectclass<?>[] Exceptiontypes = methods[0].getexceptiontypes (); Class<?>[] ExceptionTypes2 = constructors[0].getexceptiontypes (); //Get Local Propertiesfield[] Fields =Class3.getdeclaredfields (); //gets the properties of the interface or parent classfield[] Fields2 =Class3.getfields (); }}classGlyphImplementsIcon { PublicGlyph () {}}InterfaceIcon {}

Java Reflection Mechanism Example

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.