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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章