反射系列之Method方法反射
发布日期:2021-06-30 20:37:23 浏览次数:2 分类:技术文章

本文共 1021 字,大约阅读时间需要 3 分钟。

import java.lang.reflect.Method;class Preson {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}public class MethodReflect {    /**     * 调用反射类中的方法     */    public static void main(String[] args) {        try {            String attrbute = "name"; //属性名称            Class
cls = Class.forName(Preson.class.getName()); Object obj = cls.newInstance(); Method setMethod = cls.getMethod("set" + initcap(attrbute), String.class); Method getMethod = cls.getMethod("get" + initcap(attrbute)); //initcap(attrbute)返回"Name" setMethod.invoke(obj, "liuqiangaa"); //invoke相当于 实例化的类调用.setName("") System.out.println(getMethod.invoke(obj)); //相当于 例化的类调用.getName() } catch (Exception e) { e.printStackTrace(); } } //将字符串的首字母变为大写字母 public static String initcap(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1); }}

转载地址:https://liuqiang.blog.csdn.net/article/details/79760693 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:反射系列之属性Field反射
下一篇:注解之自定义注解

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月11日 01时22分46秒