[Java基础]反射获取成员方法并使用练习
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]反射获取成员方法并使用练习相关的知识,希望对你有一定的参考价值。
代码如下:
package ClassObjectPack;
public class Student {
private String name;
int age;
public String address;
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Student() {
}
private Student(String name) {
this.name = name;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
private void function()
{
System.out.println("function");
}
public void method1()
{
System.out.println("method");
}
public void method2(String s)
{
System.out.println("method:"+s);
}
public String method3(String s,int i)
{
return s+","+i;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\\'' +
", age=" + age +
", address='" + address + '\\'' +
'}';
}
}
package ClassObjectPack01;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectDemo06 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<?> c = Class.forName("ClassObjectPack.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 m4 = c.getMethod("function");
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(obj);
System.out.println(m4);
}
}
测试结果:
以上是关于[Java基础]反射获取成员方法并使用练习的主要内容,如果未能解决你的问题,请参考以下文章