• java 反射机制


    认识 java.lang.reflect包,此包下有:

    Constructor  反射类的构造方法

    Field, 反射类的属性

    Member,

    Method 反射类的方法

    Modifer

    Proxy:

    Reflect:

    ReflectAccess

    Type:

    等类.

    1.定义类

    com.daniel.reflect.Person

    2. 获取类的方法,返回一个Class object,此类对象可以用于构建对应的Object实例.

    Class personClazz;
    personClazz =Class.forName("com.daniel.reflect.Person") //抛出ReflectiveOperationException异常
    personClazz =Person.class;//
    personClazz = personObj.getclass(); //

    3. 获取实例

    Person person;
    
    a. person = (Person)personClazz.newInstance();  //需要无参的构造函数
    
    使用
    b. Constructor<?>  personCons[] =  personClazz.getConstructors();
    或者
    c. Constructor personCon = personClazz.getConstructor(String.class,int.class);
    //此外还可以使用getMethods,getFields..等来获取类方法和类属性

    4 .反射机制用于工厂模式

    package Reflect;
     
    import java.io.*;
    import java.util.*;
     
    interface fruit{
        public abstract void eat();
    }
     
    class Apple implements fruit{
        public void eat(){
            System.out.println("Apple");
        }
    }
     
    class Orange implements fruit{
        public void eat(){
            System.out.println("Orange");
        }
    }
     
    //操作属性文件类
    class init{
        public static Properties getPro() throws FileNotFoundException, IOException{
            Properties pro=new Properties();
            File f=new File("fruit.properties");
            if(f.exists()){
                pro.load(new FileInputStream(f));
            }else{
                pro.setProperty("apple", "Reflect.Apple");
                pro.setProperty("orange", "Reflect.Orange");
                pro.store(new FileOutputStream(f), "FRUIT CLASS");
            }
            return pro;
        }
    }
     
    class Factory{
        public static fruit getInstance(String ClassName){
            fruit f=null;
            try{
                f=(fruit)Class.forName(ClassName).newInstance();
            }catch (Exception e) {
                e.printStackTrace();
            }
            return f;
        }
    }
    class hello{
        public static void main(String[] a) throws FileNotFoundException, IOException{
            Properties pro=init.getPro();
            fruit f=Factory.getInstance(pro.getProperty("apple"));
            if(f!=null){
                f.eat();
            }
        }
    }

    参考:

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

  • 相关阅读:
    MySQL高性能优化规范建议,速度收藏
    基于 debian 操作系统的 docker 镜像,安装 vim
    Vue 开发经验总结
    DNS 负载均衡
    图解:从单个服务器扩展到百万用户的系统
    defer、return、返回值,这三者的执行逻辑
    goroutine 知识点
    一条SQL语句在MySQL中如何执行的
    架构设计的常用方法
    vue中直接修改props中的值并未给出警告,为啥?
  • 原文地址:https://www.cnblogs.com/waniu/p/3815900.html
Copyright © 2020-2023  润新知