一、主要方法
* <p>
* 获取所有权限构造: public Constructor<?>[] getDeclaredConstructors() throws SecurityException {}
* 获取所有public构造: public Constructor<?>[] getConstructors() throws SecurityException {}
* <p>
* 获取指定构造: public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
* throws NoSuchMethodException, SecurityException{}
* <p>
* 实例化对象(要用Constructor对象调用): public T newInstance(Object ... initargs){}
二、完整代码
package reflect.classhandle;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class GetClassConstruct {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<?>[] clazzs1 = GetClassConstructDome.class.getConstructors();
Constructor<?>[] clazzs2 = GetClassConstructDome.class.getDeclaredConstructors();
for (Constructor<?> clazz : clazzs1) {
System.out.println(clazz);
}
for (Constructor<?> clazz : clazzs2) {
System.out.println(clazz);
}
Constructor cons = GetClassConstructDome.class.getDeclaredConstructor(String.class , int.class);
Object obj = cons.newInstance("张三" , 12);
System.out.println(obj);
}
}
class GetClassConstructDome {
private String name;
private int age;
private GetClassConstructDome(int age) {
}
protected GetClassConstructDome(String name) {
}
public GetClassConstructDome() {
}
public GetClassConstructDome(String name , int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "GetClassConstructDome{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}