根据类名创建实例对象
Person person = (Person) Class.forName("com.test.test.Person").newInstance();
根据方法名执行实例对象相应的方法
Method test = Class.forName("com.test.test.Person").getMethod("test", int.class);
test.invoke(person,1);
根据方法名执行类的静态方法
Method staticTest = Class.forName("com.test.test.Person").getMethod("staticTest");
staticTest.invoke(Person.class);
根据类名获取所有域变量的名称
Field[] declaredFields = Class.forName("com.test.test.Person").getDeclaredFields();
Arrays.stream(declaredFields).forEach(field -> {
System.out.println(field.getName());
});
根据类名获取所有方法的名称【getDeclaredMethods -> 不包括超类的方法;getMethods -> 包括超类的方法】【getDeclaredMethod(methodName)获取对应方法】
Method[] methods = Class.forName("com.test.test.Person").getDeclaredMethods();
Arrays.stream(methods).forEach(method ->{
System.out.println(method.getName());
});
package com.test.test;
public class Person{
int age;
String name;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
public void test(int a){
System.out.println("this is test : "+a);
}
public static void staticTest(){
System.out.println("this is staticTest !");
}
}
package com.test.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
Person person = (Person) Class.forName("com.test.test.Person").newInstance();
person.setAge(19);
person.setName("hhj");
System.out.println(person);
Method test = Class.forName("com.test.test.Person").getMethod("test", int.class);
Method staticTest = Class.forName("com.test.test.Person").getMethod("staticTest");
test.invoke(person,1);
staticTest.invoke(Person.class);
Field[] declaredFields = Class.forName("com.test.test.Person").getDeclaredFields();
Arrays.stream(declaredFields).forEach(field -> {
System.out.println(field.getName());
});
System.out.println("-------------------------------------");
Field[] fields = Class.forName("com.test.test.Person").getFields();
Arrays.stream(fields).forEach(field -> {
System.out.println(field.getName());
});
System.out.println("-------------------------------------");
Method[] methods = Class.forName("com.test.test.Person").getMethods();
Arrays.stream(methods).forEach(method ->{
System.out.println(method.getName());
});
}
}