美文网首页
利用反射来获得方法、成员

利用反射来获得方法、成员

作者: 阿莫米德 | 来源:发表于2017-04-07 12:52 被阅读0次

    没什么好说的代码。要注意的是
    1.获得方法的修饰符的方法:Modifier.toString(met[i].getModifiers()) 它原本是用数字来表示的。比如说public是1,这里要用Modifier来把相应的数字转换成对应的修饰符
    2.获得参数用的是Class<?> params[] = met[i].getParameterTypes();

    interface Message {
        public abstract void print();
    }
    
    abstract class info {
        public abstract void get();
    }
    
    class MessageImpl extends info implements Message {
    
        @Override
        public void get() {
        }
    
        @Override
        public void print() {
        }
    
        public void set() {
        }
    
    }
    
    public class TestDemo {
        public static void main(String[] args) throws Exception {
            Class<?> cls = Class.forName("cn.mldn.demo.MessageImpl");
            Method met[] = cls.getMethods(); // cls.getMethods()获得的是所有的方法包括继承来的。
            for (int i = 0; i < met.length; i++) {
                System.out.print(
                        Modifier.toString(met[i].getModifiers()) + " " + met[i].getReturnType().getSimpleName() + " ");
                System.out.print(met[i].getName() + "(");
                Class<?> params[] = met[i].getParameterTypes();
                for (int j = 0; j < params.length; j++) {
                    System.out.print(params[j].getSimpleName() + " " + "arg");
                    if (j < params.length - 1) {
                        System.out.print(",");
                    }
                }
                System.out.print(")");
                Class<?> exp[] = met[i].getExceptionTypes();
                if (exp.length > 0) {
                    System.out.print(" throws ");
                    for (int j = 0; j < exp.length; j++) {
                        System.out.print(exp[j].getSimpleName() + " ");
                        if (j < exp.length - 1) {
                            System.out.print(",");
                        }
                    }
                }
                System.out.println();
            }
        }
    }
    

    以下是对方法的调用,一般来说我们要把类中的成员封装。用invoke来调用。

    import java.lang.reflect.Method;
    import cn.mldn.util.StringUtil;
    
    class Message {
        private String content;
        public String print(String str){
            return str;
        }
        public String getContent() {
            return content;
        }
        public void setContent(String content) {
            this.content = content;
        }
    }
    
    public class TestDemo {
        public static void main(String[] args) throws Exception {
            String classname = "cn.mldn.demo.Message";
            String property = "content";
            String value = "北京下雨了";
            Class<?> cls = Class.forName(classname);
            Method setMet = cls.getMethod("set"+StringUtil.initcap(property), 
    String.class);//这里必须固定好参数的类型,增加了耦合
            Method getMet = cls.getMethod("get"+StringUtil.initcap(property));
            Object obj = cls.newInstance();
            setMet.invoke(obj, value);
            System.out.println(getMet.invoke(obj));
        }
    }
    

    上面必须固定参数类型,我们可以通过Field类来优化。

    反射的reflect包中最核心的类一共有三个:Construct,Field,Method
    Fidle就是成员。不要直接通过反射进行属性的调用。

    field.setAccessible(true)
    

    虽然这个方法可以破坏类的封装,让我们直接使用成员的值。但是不要用。

    public class TestDemo {
        public static void main(String[] args) throws Exception {
            String classname = "cn.mldn.demo.Message";
            String property = "content";
            String value = "北京下雨了";
            Class<?> cls = Class.forName(classname);
            Field field = cls.getDeclaredField(property);
            Method setMet = cls.getMethod("set"+StringUtil.initcap(property), 
    field.getType());//获得成员的类型
            Method getMet = cls.getMethod("get"+StringUtil.initcap(property));
            Object obj = cls.newInstance();
            setMet.invoke(obj, value);
            System.out.println(getMet.invoke(obj));
        }
    }
    

    相关文章

      网友评论

          本文标题:利用反射来获得方法、成员

          本文链接:https://www.haomeiwen.com/subject/gfxhattx.html