反射获取成员方法并使用练习
public class ReflectDemo04 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.reflect_02.Student"); Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); Method m1 = c.getMethod("method1"); m1.invoke(obj); Method m2 = c.getMethod("method2", String.class); m2.invoke(obj,"林青霞"); Method m3 = c.getMethod("method3", String.class, int.class); Object o = m3.invoke(obj, "林青霞", 30); System.out.println(o); Method function = c.getDeclaredMethod("function"); function.setAccessible(true); function.invoke(obj); } }
运行结果:
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。