• 读书笔记_java设计模式深入研究 第二章 反射


    1,JDK中反射类包含的内容:
        -1,Class类,代表一个类。
        -2,Constructor,代表类的构造方法。
        -3,Field,代表类成员
        -4,Method,代表方法。
    2,统一调用形式:
        一个基本的使用反射的例子如下:
    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(){
            
        }
        /**
         * 带参数的构造方法
         * @param m
         */
        public A(int m){
            
            this.= m;
        }
        /**
         * 
         */
        public void func(){
            
            System.out.println("Hello Java!");
        }
        
        public static void main(String[] args) throws Exception {
            
            //加载A类对应的Class
            //Class<A> clazz = A.class;
            //此方法需要对类的全路径
            Class<?> clazz = Class.forName("com.use.A");
            
            //获取类对应的构造函数
            System.out.println("A 对应构造函数:");
            Constructor<?> cons[] = clazz.getConstructors();
            
            for(Constructor<?> con : cons){
                
                System.out.println(con.toString());
            }
            
            //获取A对应的变量
            System.out.println("A 对应变量: ");
            Field fields[] = clazz.getDeclaredFields();
            
            for(Field field: fields){
                
                System.out.println(field.toString());
            }
            
            //获取A对应的方法
            System.out.println("A对应的方法: ");
            Method[] methods = clazz.getDeclaredMethods();
            for(Method method: methods){
                
                System.out.println(method.toString());
            }
            
        }
    }
        以下例子为对应通过反射使用构造函数生成对象:
       
     package com.use;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    /**
     * 通过反射,使用构造函数生成对象
     * @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:  " + " m = " + m
                    + ", s = " + s);
        }
        
        public static void main(String[] args) throws  Exception{
            //get Class
            Class<?> clazz = Class.forName("com.use.ReflectionMethod");
            //获取到对应类型的构造函数,通过构造Constructor的newInstance方法
            Constructor<?> cons[] = clazz.getConstructors();
             
            cons[2].newInstance();
            cons[1].newInstance(1);
            cons[0].newInstance(3, "abc");
            
            //通过Class对象对应的具体的Constructor,然后生成对象
            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");
            
        }
    }
     以下方式为通过反射调用对应对象的方法:
    package com.use;
    import java.lang.reflect.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,反射与配置文件
        通过配置文件,使用反射生成不同的对象。
    package com.properties;
    /**
     * 图形接口 
     * @author Mergades
     *
     */
    public interface IShape {
        /**
         * 输入方法
         * 
         * @return
         */
        boolean input();
        
        /**
         * 获取图形对应的面积
         * @return
         */
        float getArea();
    }  
    package com.properties;
    /**
     * 图形处理类
     * @author Mergades
     *
     */
    public class ShapeProc {
        /**
         * 图形对象
         */
        private IShape shape;
        
        public ShapeProc(IShape shape){
            
            this.shape = shape;
        }
        /**
         * 获取对应图形的面积
         * @return
         */
        public float process(){
            
            shape.input();
            float value = shape.getArea();
            return value;
        }
    }
    package com.properties;
     
    import java.util.Scanner;
     
    /**
    * 圆
    *
    * @author Mergades
    *
    */
    public class Circle implements IShape {
     
    float r;// 半径
     
    @Override
    public boolean input() {
     
    System.out.println("请输入半径: ");
    @SuppressWarnings("resource")
    Scanner s = new Scanner(System.in);
    r = s.nextFloat();
    return true;
    }
     
    @Override
    public float getArea() {
     
    float s = (float) (Math.PI * r * r);
    return s;
    }
     
    }
    package com.properties;
     
    import java.util.Scanner;
     
    /**
    * 矩形
    * @author Mergades
    *
    */
    public class Rect implements IShape {
    float width, height;
    @Override
    public boolean input() {
    System.out.println("请输入宽、高 : ");
    @SuppressWarnings("resource")
    Scanner s = new Scanner(System.in);
    width = s.nextFloat();
    height = s.nextFloat();
    return true;
    }
     
    @Override
    public 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);
    }
    }
    对应目录结构:





































    欢迎转载,但转载请注明原文链接[博客园: http://www.cnblogs.com/jingLongJun/]
    [CSDN博客:http://blog.csdn.net/mergades]。
    如相关博文涉及到版权问题,请联系本人。
  • 相关阅读:
    hadoop02---高可用网站架构
    springboot-vue项目前台2
    Java Serializable(序列化)
    JAVA 正则表达式、汉字正则、 java正则代码
    MyEclipse导入Maven项目
    JAVA学习:maven开发环境快速搭建
    删除
    关于java程序打包为EXE的若干问题
    ServletContext与ServletConfig的详解及区别
    在CSS中定义a:link、a:visited、a:hover、a:active顺序
  • 原文地址:https://www.cnblogs.com/jingLongJun/p/4491076.html
Copyright © 2020-2023  润新知