回顾: Class 对象:在加载类时由 Java 虚拟机以及通过调用类加载器中的 defineClass 方法自动构造的。通过Class实例得到类的信息的手段成为反射
Class对象获取的三种法法:
//方法一:Class class对象名 = 类名.class
Class cls1 = String.class;
//方法二:Class class对象名 = 对象.getClass()
String s = "chengyuan";
Class cls2 = s.getClass();
//方法三:Class class对象名 = Class.forName("类名");
Class cls3 = Class.forName("java.lang.String");
本文重点:
1、Class.newInstance()只能调用public的无参构造方法
2、Constructor对象:通过Class的实例获取Constructor对象
Constructor<T> getConstructor(Class<?>... parameterTypes) 返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法。
Constructor<?>[] getConstructors() 返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法。
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法。
Constructor<?>[] getDeclaredConstructors() 返回 Constructor 对象的一个数组,这些对象反映此 Class 对象表示的类声明的所有构造方法。
注意:不可以通过Class实例直接获取父类的构造方法,这部分将在后面做阐述。
代码演示:
public class ReflectionConstructor {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//直接调用无参构造:jdk:10已过时
//var constructor = Constructor.class.newInstance();
//通过Class的实例获取Constructor对象
Con cl = new Con();
Class cls =cl.getClass();
cls.getConstructor();
cls.getConstructor(String.class);
cls.getConstructors();
cls.getDeclaredConstructor(String.class, int.class);
cls.getDeclaredConstructors();
//破话封装性:改变修饰符为private
Constructor c = cls.getDeclaredConstructor(String.class, int.class);
c.setAccessible(true);
Con obj = (Con)c.newInstance("悦影",20);
}
}
class Con{
String name ;
int age;
public Con(String name) {
this.name = name;
}
Con() {
}
private Con(String name, int age){
this.name= name;
this.age= age;
}
}
无参构造String类的反射方式调用
public class ReflectionConstructor {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//直接调用无参构造:jdk:10已过时
//var constructor = Constructor.class.newInstance();
//通过Class的实例获取Constructor对象
String cl = new String();
Class cls =cl.getClass();
Constructor constructor = cls.getConstructor();
Constructor[] constructors = cls.getConstructors();
//破话封装性:改变修饰符为private
//调用String的构造方法:创建一个空字符串的对象 等价于: String str = new String();
String str = (String)constructor.newInstance();
str = str.replace("","悦影");
System.out.println(str);
}
}