Class对象功能概述和Class对象功能获取Field
Constructor[] getConstructors()
Constructor getConstructor(类... parameterTypes)
Constructor getDeclareConstructor(类... paramterTypes)
Constructor[] getDeclaredConstructors()获取所有的成员变量不考虑修饰符
Constructor:构造方法
创建对象
T newUnstance(Object... initargs)
如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法
package com.yang.reflect;
import com.yang.exercises.Person;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectStudy02 {
public static void main(String[] args) throws Exception {
/**
* 2.获取构造方法们
* Constructor[] getConstructors()
* Constructor getConstructor(类... parameterTypes)
*
* Constructor getDeclareConstructor(类... paramterTypes)
* Constructor[] getDeclaredConstructors()获取所有的成员变量不考虑修饰符
*/
Class<Person> personClass = Person.class;
//Constructor getConstructor(类... parameterTypes)
Constructor<Person> constructor = personClass.getConstructor(String.class, int.class);
System.out.println(constructor);
//创建对象
Person p = constructor.newInstance("张三", 18);
System.out.println(p);
Person person = personClass.newInstance();
System.out.println(person);
}
}
Class对象功能获取Field
package com.yang.reflect;
import com.yang.exercises.Person;
import java.lang.reflect.Method;
public class ReflectStudy03 {
public static void main(String[] args) throws Exception {
/**
3.获取成员方法们
Method[] getMethod()
Method getMethod(String name,类<?>... paramterTypes)
Method[] getDeclaredMethods()
Method getDeclaredMethod(String name,类<?>... paramterTypes)
*/
//获取Person的class对象
Class<Person> personClass = Person.class;
//获取指定名称的方法
Method eat = personClass.getMethod("eat");
Person p = new Person();
//执行方法
eat.invoke(p);
Method eat2 = personClass.getMethod("eat",String.class);
//执行方法
eat2.invoke(p,"饭");
//获取所有public修饰的方法
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println(method);
String name = method.getName();
System.out.println(name);
}
//获取类名
String className = personClass.getName();
System.out.println(className);
}
}