import java.lang.reflect.Method; class Person { private String name ; public void setName(String name) { this.name = name; } public String getName() { return name; } } public class TestDemo { public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("cn.mldn.demo.Person") ; Object obj = cls.newInstance(); String attribute = "name" ; Method setMet = cls.getMethod("set" + initcap(attribute), String.class); Method getMet = cls.getMethod("get" + initcap(attribute)); setMet.invoke(obj, "张三") ; System.out.println(getMet.invoke(obj)); } public static String initcap(String str) { return str.substring(0,1).toUpperCase().concat(str.substring(1)) ; } }
谁能帮忙加加注释,尽量详细点,看着好费劲,搞不明白!真心感谢啊!
|