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

你可能感兴趣的:(java 反射)