In-depth research on java design patterns (reflection)

Source: Internet
Author: User

In-depth research on java design patterns (reflection)
1. The reflection Class in JDK contains:-1, Class, representing a Class.
-2, Constructor, representing the class Constructor.
-3, Field, representing class members
-4, Method, representing the Method.
2. Unified Call form: An Example of basic reflection usage is as follows:

package com.use;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class A {    int m;//m        /**     * empty constructor     */    public A(){            }    /*** Construction Method with Parameters     * @param m     */    public A(int m){                this.m = m;    }    /**     *      */    public void func(){                System.out.println("Hello Java!");    }        public static void main(String[] args) throws Exception {        // Load the Class corresponding to Class        //Class clazz = A.class;// This method requires the full path of the class        Class
   clazz = Class.forName("com.use.A");        // Obtain the constructor corresponding to the classSystem. out. println ("A corresponding constructor :");        Constructor
   cons[] = clazz.getConstructors();                for(Constructor
   con : cons){                        System.out.println(con.toString());        }        // Obtain the variable corresponding toSystem. out. println ("A corresponding variable :");        Field fields[] = clazz.getDeclaredFields();                for(Field field: fields){                        System.out.println(field.toString());        }        // Obtain the method corresponding toSystem. out. println ("A corresponding method :");        Method[] methods = clazz.getDeclaredMethods();        for(Method method: methods){                        System.out.println(method.toString());        }            }}
The following example shows how to generate an object using constructor through reflection:
 package com.use;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;/*** Use constructor to generate objects through reflection * @author Mergades * */public class ReflectionMethod {    public ReflectionMethod() {        System.out.println("Empty Constructor!");    }    public ReflectionMethod(Integer m) {        System.out.println("Constructor with args: " + m);    }    public ReflectionMethod(Integer m, String s) {        System.out.println("Constructor with double args: \n" + " m = " + m                + ", s = " + s);    }        public static void main(String[] args) throws  Exception{        //get Class        Class
   clazz = Class.forName("com.use.ReflectionMethod");// Obtain the corresponding Constructor type by constructing the newInstance method of Constructor        Constructor
   cons[] = clazz.getConstructors();                 cons[2].newInstance();        cons[1].newInstance(1);        cons[0].newInstance(3, "abc");        // Use the specific Constructor corresponding to the Class object, and then generate the object        Constructor
   c = clazz.getConstructor();        c.newInstance();                Constructor
   cSingleArgs = clazz.getConstructor(Integer.class);        cSingleArgs.newInstance(3);        Constructor
   cDoubleArgs = clazz.getConstructor(Integer.class, String.class);        cDoubleArgs.newInstance(3, "s");            }}
The following method calls the corresponding object through reflection:
package com.use;import java.lang.reflect.Method;/*** Reflection call Method * @author Mergades * */public class MethodInvoke {    public void func1(){                System.out.println("Function func1");    }        public void func2(int m){                System.out.println("Function func2,args : " + m);    }    public void func3(int m, String s){                System.out.println("Function func3, args : m :" + m + ", s:" + s);    }        public static void main(String[] args) throws Exception {                Class
   clazz = Class.forName("com.use.MethodInvoke");                Object obj = clazz.getConstructor().newInstance();                Method m1 = clazz.getMethod("func1");        m1.invoke(obj);                m1 = clazz.getMethod("func2", int.class);        m1.invoke(obj, 3);                m1 = clazz.getMethod("func3", int.class, String.class);        m1.invoke(obj, 3, "s");    }}
3. Reflection and configuration files use reflection to generate different objects through the configuration file.
package com.properties;/*** Graphic interface * @author Mergades * */public interface IShape {    /*** Input Method     *      * @return     */    boolean input();        /*** Obtain the area corresponding to the image.     * @return     */    float getArea();}  
package com.properties;/*** Graphic Processing * @author Mergades * */public class ShapeProc {    /*** Graphic objects     */    private IShape shape;        public ShapeProc(IShape shape){                this.shape = shape;    }    /*** Obtain the area of the corresponding image.     * @return     */    public float process(){                shape.input();        float value = shape.getArea();        return value;    }}
package com.properties; import java.util.Scanner; /*** Circle *  * @author Mergades * */public class Circle implements IShape { Float r; // radius @Overridepublic boolean input() { System. out. println ("Enter the radius :");@SuppressWarnings("resource")Scanner s = new Scanner(System.in);r = s.nextFloat();return true;} @Overridepublic float getArea() { float s = (float) (Math.PI * r * r);return s;} }
package com.properties; import java.util.Scanner; /*** Rectangle * @author Mergades * */public class Rect implements IShape {float width, height;@Overridepublic boolean input() {System. out. println ("Enter width and height :");@SuppressWarnings("resource")Scanner s = new Scanner(System.in);width = s.nextFloat();height = s.nextFloat();return true;} @Overridepublic float getArea() {float s =  width * height;return s;} }

package com.properties; import java.util.Properties; public class Test { public static void main(String[] args) throws Exception {Properties p = new Properties(); p.load(new Test().getClass().getResourceAsStream("shape.properties"));//System.out.println(p.getProperty("shape")); String className = p.getProperty("shape");IShape shape = null;shape = (IShape) Class.forName(className).getConstructor().newInstance();ShapeProc proc = new ShapeProc(shape);float value = proc.process();System.out.println(value);}}

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.