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

没什么好说的代码。要注意的是
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));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 整体Retrofit内容如下: 1、Retrofit解析1之前哨站——理解RESTful 2、Retrofit解析...
    隔壁老李头阅读 10,126评论 2 12
  • Java反射 概述 Java反射机制可以让我们在编译期(Compile Time)之外的运行期(Runtime)检...
    Leocat阅读 4,822评论 0 0
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 9,784评论 0 16
  • 前言 人生苦多,快来 Kotlin ,快速学习Kotlin! 什么是Kotlin? Kotlin 是种静态类型编程...
    任半生嚣狂阅读 26,553评论 9 118
  • (对于不能相守的异地恋人,思念会象万虫噬咬,百蚁爬行。七夕来临之际,仅以此诗,献给所有不能相聚的“牛郎织女”,祝节...
    梅子的山园阅读 3,196评论 7 3

友情链接更多精彩内容