java反射

API使用

package com.lesserPand.springIOC.test;

import java.util.List;

import org.apache.commons.lang.StringUtils;

public class Input {

    /**
     * @Fields serialVersionUID :
     */
    private static final long serialVersionUID = 1138768477136281501L;

    /**
     * @Fields type : 提交參數類型 post、 upload、download
     */
    public String type;

    public String t;

    public int t1;

    private String tt;

    /**
     * @Fields parameter : 提交參數
     */
    public List<Parameter> parameter;

    /**
     * @Description: 獲取 json 對應的存儲過程
     * @Author:pand
     * @Since: 2015年12月30日上午10:16:31
     * @param list
     * @return
     */
    public Parameter getJsonProceduresParameter() {
        for (Parameter item : parameter) {
            // <parameter name="remark1" type="json"
            // procedures="p_app_gov_hd_update_dealmode_upd" ></parameter>
            if ("json".equals(item.getType()) && StringUtils.isNotBlank(item.getProceduresName())) {
                return item;
            }
        }
        return null;
    }

    public Input() {
        super();
    }

    public Input(String type) {
        super();
        this.type = type;
    }

    private Input(String type, String t) {
        super();
        this.type = type;
        this.t = t;
    }

    public Input(String type, List<Parameter> parameter) {
        super();
        this.type = type;
        this.parameter = parameter;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getT() {
        return t;
    }

    public void setT(String t) {
        this.t = t;
    }

    public int getT1() {
        return t1;
    }

    public void setT1(int t1) {
        this.t1 = t1;
    }

    public String getTt() {
        return tt;
    }

    public void setTt(String tt) {
        this.tt = tt;
    }

    public List<Parameter> getParameter() {
        return parameter;
    }

    public void setParameter(List<Parameter> parameter) {
        this.parameter = parameter;
    }
}

package com.lesserPand.springIOC.test;

import java.util.List;

public class InputService {

    public String getInput(String id){
        System.out.println("調用id = "+id);
        return "1";
    };

    public List<Input> getInputs(){

        System.out.println("調用空 = ......"+10);
        return null;
    };

    private Input getInputByOther(String id, String t){
        System.out.println("調用id = "+id + "t = "+t);
        return null;
    };

}

示例代碼

package com.lesserPand.springIOC.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.lesserPand.springIOC.test.Input;
/**
 * Class反射,常用api
 * int getModifiers();//獲得修飾符
 * String getName();//返回類的全限定名
 * Package getPackage();//獲取該類的包
 * String getSimpleName();//獲取該類的簡單名字
 * Class getSuperclass();//獲取該類的父類
 * boolean isArray();//判斷該Class實例是否是數據
 * boolean isEnum();//判斷該Class實例是否是枚舉
 * 更多信息,查看api
 * @author Administrator
 *
 */
public class FsDemo {

    public static void main(String[] args) {
        try {
            /*int modifier = Class.forName("com.lesserPand.springIOC.utils.FsDemo").getModifiers();
            System.out.println(modifier);
            String modifiers = Modifier.toString(modifier);
            System.out.println(modifiers);
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").getName());
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").getPackage());
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").getSimpleName());
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").getSuperclass());
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").isArray());
            System.out.println(Class.forName("com.lesserPand.springIOC.utils.FsDemo").isEnum());*/
            //getUserClass();
            //getConstructors();
            //getOneConstruceor();
            //getMethod();
            //userMethod();
            //userStaticMethod();
            //getField();
            //setField();
            //userfx();
            getFx();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void getUserClass() throws ClassNotFoundException{
        Class clazz = Input.class;
        System.out.println(clazz);

        Input input = new Input();
        Class clazz1 = input.getClass();
        System.out.println(clazz1);

        Class clazz2 = Class.forName("com.lesserPand.springIOC.test.Input");
        System.out.println(clazz2);

    }
    /**
     * 獲取構造器
     * @throws ClassNotFoundException
     */
    public static void getConstructors() throws ClassNotFoundException{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.test.Input");
        //獲取全部public的構造器
        Constructor<?>[] constructors1 = clazz.getConstructors();
        for(Constructor<?> constructor : constructors1){
            System.out.println(constructor);
        }

        //獲取全部構造器
        Constructor<?>[] constructors2 = clazz.getDeclaredConstructors();
        for(Constructor<?> constructor : constructors2){
            System.out.println(constructor);
        }
    }

    /**
     * 通過構造器創建實例
     * @throws ClassNotFoundException
     */
    public static void getOneConstruceor() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.test.Input");
        //獲取無參構造器
        Constructor<?> constructor1 = clazz.getConstructor();
        Input input1 = (Input) constructor1.newInstance();

        //獲取一個public有參數構造器
        Constructor<?> constructor2 = clazz.getConstructor(String.class);
        Input input2 = (Input) constructor2.newInstance("張三");

        //獲取一個私有有參構造器
        Constructor<?> constructor3 = clazz.getDeclaredConstructor(String.class, String.class);
        constructor3.setAccessible(true);//設置忽略檢查
        Input input3 = (Input) constructor3.newInstance("李四", "22");

        System.out.println(input1);
        System.out.println(input2+"  ==  "+input2.getType());
        System.out.println(input3+"  ==  "+input3.getType()+"  ==  "+input3.getT());
    }

    /**
     * 獲取方法
     * @throws Exception
     */
    public static void getMethod() throws Exception{
        Class<?> clazz1 = Class.forName("com.lesserPand.springIOC.test.InputService");
        //獲取包括object的方法
        Method[] methods1 = clazz1.getMethods();
        for(Method method : methods1){
            System.out.println(method);
        }
        System.out.println("====================================================");

        //獲取自身方法
        Method[] methods2 = clazz1.getDeclaredMethods();
        for(Method method : methods2){
            System.out.println(method);
        }

        System.out.println("====================================================");
        //根據入參獲取自身私有方法,
        Method method3 = clazz1.getDeclaredMethod("getInputByOther", String.class, String.class);
        System.out.println(method3);

        System.out.println("====================================================");
        //根據入參獲取自身public方法,
        Method method4 = clazz1.getMethod("getInput", String.class);
        System.out.println(method4);
    }

    /**
     * 通過反射調用方法
     * @throws Exception
     */
    public static void userMethod() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.test.InputService");
        Constructor<?> constructor= clazz.getConstructor();

        Method method1 = clazz.getMethod("getInput", String.class);
        String id = (String) method1.invoke(constructor.newInstance(), "10");//顯示調用無參構造器
        String id1 = (String) method1.invoke(clazz.newInstance(), "10");//默認調用無參構造器
        System.out.println("回調id="+id);
        System.out.println("回調id1="+id1);
    }

    /**
     * 使用反射調用靜態方法和可變參數方法
     * @throws Exception 
     */
    public static void userStaticMethod() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.utils.FsDemo");

        Method staticMethod = clazz.getMethod("userMethod");
        staticMethod.invoke(null);//靜態方法屬於類的,調用時忽略指定obj參數,設爲null即可

        //調用可變參數方法,可變參數都用object包裹一下(即時基本類型不用,也用Object包裹),可避免錯誤。
        Method paramMethod = clazz.getMethod("userChangeParamMethod", String[].class);//根據方法名和參數類型獲取方法
        paramMethod.invoke(null, new Object[]{new String[]{"a","b","c"}});//調用方法

    }

    /**
     * 可變參數方法
     */
    public static void userChangeParamMethod(String ... arge){
        System.out.println(Arrays.toString(arge));
    }

    /**
     * 通過反射獲取字段
     * @throws ClassNotFoundException 
     * @throws SecurityException 
     * @throws NoSuchFieldException 
     */
    public static void getField() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.test.Input");

        //根據字段名稱獲取public字段
        Field field = clazz.getField("type");
        System.out.println(field);

        //根據名稱獲取私有字段
        Field privatefield = clazz.getDeclaredField("tt");
        System.out.println(privatefield);

        //獲取public
        Field[] fields = clazz.getFields();
        System.out.println(Arrays.toString(fields));

        //獲取所有字段,包括public和private
        Field[] privatefields = clazz.getDeclaredFields();
        System.out.println(Arrays.toString(privatefields));
    }

    /**
     * 給字段設置值
     * @throws Exception
     */
    public static void setField() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.test.Input");

        Input input = (Input)clazz.newInstance();

        Field field = clazz.getField("type");
        Field fieldt = clazz.getField("t1");
        field.set(input, "張三");//字段爲static,set(Object, value),Object設置爲null
        fieldt.set(input, 20);

        System.out.println(input + "  " + field.get(input) +"  "+fieldt.get(input));//get(Object),static將Object設置爲null
    }

    //調用泛型方法
    public static void userfx() throws Exception{
        Class<?> clazz = Class.forName("java.util.Arrays");
        Method method = clazz.getMethod("asList", Object[].class);//入參是泛型,參數設置爲Object[].class
        System.out.println(method.getName());
        List list = (List)method.invoke(null, new Object[]{new Object[]{"a","b"}});//靜態方法,invoke(Object,param);,Object設置爲null
        System.out.println(list);
    }

    public Map<String, Object> map;

    /**
     * 獲取泛型參數
     */
    public static void getFx() throws Exception{
        Class<?> clazz = Class.forName("com.lesserPand.springIOC.utils.FsDemo");

        Field field = clazz.getField("map");
        Type type = field.getType();
        Type genericType = field.getGenericType();//獲取參數泛型的類型
        System.out.println(type +" === " +genericType);
        ParameterizedType pType = (ParameterizedType)genericType;
        Type[] types = pType.getActualTypeArguments();
        System.out.println(Arrays.toString(types));
    }
}

泛型工廠類,創建實例

package com.lesserPand.springIOC.utils;

import java.util.Date;

/**
 * 泛型工廠類,創建實例
 * @author Administrator
 *
 */
public class FsFactoryUtil {

    public static FsFactoryUtil fsFactoryUtil = null;

    private FsFactoryUtil(){}

    private static synchronized FsFactoryUtil getInstance(){
        if(null == fsFactoryUtil){
            fsFactoryUtil = new FsFactoryUtil();
        }
        return fsFactoryUtil;
    }

    private <T>T getBean(String className, Class<T> clazz){
        try {
            Class<?> cla = Class.forName(className);
            Object object = cla.newInstance();

            if(!clazz.isInstance(object)){
                throw new IllegalAccessError("");
            }else{
                return (T)object;
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

枚舉單例設計模式


package com.lesserPand.springIOC.utils;


public enum FsEnumFactoryUtil {
    INSTANCE;

    public <T> T createInstance(String className, Class<T> clazz) {

        try {
            Object obj = Class.forName(className).newInstance();
            if (!clazz.isInstance(obj)) {
                throw new IllegalAccessError("異常");
            } else {
                return (T) obj;
            }
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

調用

package com.lesserPand.springIOC.utils;

import java.util.Date;

/**
 * 泛型工廠類,創建實例
 * @author Administrator
 *
 */
public class FsFactory {

    public static void main(String[] args) {
        String name = "java.util.Date";
        Date date = null;
        date = createInstance(name, Date.class);
        System.out.println(date.toLocaleString());


        /*XXXX xxxx = FsEnumFactoryUtil.INSTANCE.getInstance();
        xxxx.createInstance(name, Date.class);
        System.out.println(date.toLocaleString());*/

        FsEnumFactoryUtil.INSTANCE.createInstance(name, Date.class);
        System.out.println(date.toLocaleString());
    }

    public static <T>T createInstance(Class<T> clazz){
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 創建實例工廠
     * @param name
     * @param checkType
     * @return
     */
    public static <T>T createInstance(String name, Class<T> checkType){
        Class<T> clazz;
        try {
            clazz = (Class<T>)Class.forName(name);
            Object object = clazz.newInstance();
            if(!checkType.isInstance(object)){
                throw new IllegalAccessException("異常");
            }
            return (T)object;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章