Java反射机制

问题描述:

       java反射机制

 

参考资料:

      1、http://blog.csdn.net/nieweilin/article/details/5908165

      2、http://www.cnblogs.com/shiyangxt/archive/2008/11/03/1325832.html

名词解释:

          什么是Java反射机制:

      Java反射式Java被视为动态(或准动态)语言的一个特质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的

class的内部信息,其中包括modifiers(如public和static等)、SuperClass(例如Object)、实现的Interface,也包括类的字段和方法的

所有信息,并可于运行时改变字段(field)的值或者调用成员函数(methods)。Java的反射机制容许程序在运行时加载、探知、使用编译期间

完全未知的classes,也就是说Java可以加载一个运行时才得知名称的class,获取其完整结构。

 

        实现Java反射机制的常用方法:

             image

 

            image

具体实例:

         Example.java 文件

package com.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Example {
    public static int id = 0;
    public int count = ++id;
    private static int val = 2;

    public static int getId() {
        return id;
    }

    private static int getVal() {
        return val;
    }

    public int getCount() {
        return count;
    }

    public static int setId(Integer id) {
        Example.id = id;
        return Example.id;
    }

    public int setCount(Integer count) {
        int temp = this.count;
        this.count = count;
        return temp;
    }

    public Example(Integer count) {
        this.setCount(count);
    }

    public Example() {

    }

    public static void main(String[] args) {
        Example example = new Example();
        Class
<?> exampleClass =
 example.getClass();
        Method[] methods 
=
 exampleClass.getDeclaredMethods();
        System.out.println("============DeclaredMethods=========");
        for (Method m : methods) {
            System.out.println(m.getName());
        }

        System.out.println("============DeclaredFields=========");
        Field[] fields 
=
 exampleClass.getDeclaredFields();
        for (Field f : fields) {
            System.out.println(f.getName());
        }
    }
}

 

Reflection.java 文件:

package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Reflection {

    /**
     * 获得对象的public字段值
     * 
     * @param ownner
     * @param fieldName
     * @return
     */
    public Object getProperty(
Object ownner
, String fieldName) throws Exception {

        Class
<?> ownnerClass =
 ownner.getClass();
        Field field = ownnerClass.getField(fieldName);
        Object property = field.get(ownner);
        return property;
    }

    /**
     * 获得对象的public static字段值
     * 
     * @param className
     * @param fieldName
     * @return 方法返回结果
     */
    public Object getStaticProperty(String className, String fieldName)
            throws ClassNotFoundException, NoSuchFieldException,
            SecurityException, IllegalArgumentException, IllegalAccessException {

        Class
<?> ownnerClass =
 Class.forName(className);
        Field field = ownnerClass.getField(fieldName);
        Object property = field.get(fieldName);
        return property;
    }

    /**
     * 调用对象的public非static方法
     * 
     * @param ownner
     * @param methodName
     * @param args
     * @return
     */
    public Object invokeMethod(Object ownner, String methodName, Object[] args)
            throws Exception {

        Class
<?> ownnerClass =
 ownner.getClass();
        int len = args.length;
        Class<?>[] argsClass = new Class[len];
        for (int i = 0; i < len; i++) {
            argsClass[i] = args[i].getClass();
        }
        Method method 
=
 ownnerClass.getMethod(methodName, argsClass);
       return method.invoke(ownner, args);
    }

    /**
     * 调用类的静态方法(static method)
     * 
     * @param className
     * @param methodName
     * @param args
     * @return
     * @throws Exception
     */
    public Object invokeStaticMethod(String className, String methodName,
            Object[] args) throws Exception {

        Class
<?> ownnerClass =
 Class.forName(className);
        int len = args.length;
        Class<?>[] argsClass = new Class[len];
        for (int i = 0; i < len; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method 
=
 ownnerClass.getMethod(methodName, argsClass);
        
return method.invoke(null
, args);
    }

    /**
     * 调用类的静态方法(static method)
     * 
     * @param ownner
     * @param methodName
     * @param args
     * @return
     * @throws Exception
     */
    public Object invokeStaticMethod(Object ownner, String methodName,
            Object[] args) throws Exception {

        Class<?> ownnerClass = ownner.getClass();
        int len = args.length;
        Class<?>[] argsClass = new Class[len];
        for (int i = 0; i < len; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method 
=
 ownnerClass.getMethod(methodName, argsClass);
      
return method.invoke(null
, args);
    }

    /**
     * 包含参数构造函数
     * 
     * @param className
     * @param args
     * @return
     * @throws Exception
     */
    public Object newInstance(
String className,
 Object[] args) throws Exception {
        Class
<?> ownnerClass = Class.forName(className); Class<?>[] argsClass = new
 Class[args.length];
        for (int i = 0; i < args.length; i++) {
            argsClass[i] = args[i].getClass();
        }
        Constructor
<?> constructor =
 ownnerClass.getConstructor(argsClass);
        return constructor.newInstance(args);
    }

    /**
     * 无参构造函数
     * 
     * @param className
     * @return
     */
    public Object newInstance(
String className
) throws Exception {
        Class<?> ownnerClass = Class.forName(className);
        Constructor
<?> cons =
 ownnerClass.getConstructor();
      return cons.newInstance();
    }

    /**
     * 查看对象是否是某个类的实例
     * 
     * @param object
     * @param className
     * @return
     * @throws Exception
     */
    public boolean isInstance(Object object, String className) throws Exception {
        Class
<?> ownnerClass = Class.forName(className); return
 ownnerClass.isInstance(object);
    }

    public static void main(String[] args) {
        Reflection reflection = new Reflection();

        try {
            Example example = (Example) reflection.newInstance(
                    "com.reflection.Example", new Object[] { new Integer(33) });

            System.out.println("isInstance:"
                    + reflection.isInstance(example, "com.reflection.Example"));

            System.out.println("count:"
                    + reflection.getProperty(example, "count"));

            System.out.println("public setCount():"
                    + reflection.invokeMethod(example, "setCount",
                            new Object[] { 12 }));
            System.out.println("count:"
                    + reflection.getProperty(example, "count"));

            System.out.println("===============================");

            System.out.println("static id:"
                    + reflection.getStaticProperty("com.reflection.Example",
                            "id"));
            System.out.println("public static setId():"
                    + reflection.invokeStaticMethod(example, "setId",
                            new Object[] { new Integer(8) }));
            System.out.println("static id:"
                    + reflection.getStaticProperty("com.reflection.Example",
                            "id"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            System.out.println("===============================");
            Example example 
= (Example) reflection .newInstance("com.reflection.Example"
);  //注意:这里使用类名称生成Class类型,需要使用类的路径(包括包名)

            System.out.println("isInstance:"
                    + reflection.isInstance(example, "com.reflection.Example"));

            System.out.println("count:"
                    + reflection.getProperty(example, "count"));

            System.out.println(
"public setCount():" + reflection.invokeMethod(example, "setCount", new Object[] { 12
 }));
            System.out.println("count:"
                    + reflection.getProperty(example, "count"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

注:

     在使用反射机制,调用实际类中方法时,反射类中函数调用参数为Integer,实际类中方法参数为int

出现如下错误:

     image

具体详情如下:

Example.java 文件:
       public int setCount(int count) {
        int temp = this.count;
        this.count = count;
        return temp;
    }

Reflection.java 文件:
    /**
     * 调用对象的public非static方法
     * 
     * @param ownner
     * @param methodName
     * @param args
     * @return
     */
    public Object invokeMethod(Object ownner, String methodName, Object[] args)
            throws Exception {

        Class<?> ownnerClass = ownner.getClass();
        int len = args.length;
        Class<?>[] argsClass = new Class[len];
        for (int i = 0; i < len; i++) {
            argsClass[i] = args[i].getClass();
        }
        Method method = ownnerClass.getMethod(methodName, argsClass);
        return method.invoke(ownner, args);
    }

main函数:
    Example example = (Example) reflection
                    .newInstance("com.reflection.Example");

       System.out.println("public setCount():"
                    + reflection.invokeMethod(example, "setCount",
                         
new Object[] { 12 })); //注:在调用Example.java 中setCount函数时,会报错:NoSuchMethodException,解决方法 ,修改Example.java 中setCount(int count)为setCount(Integer count)可正确运行。
posted @ 2013-11-29 11:53  罗松超  阅读(532)  评论(0编辑  收藏  举报