进阶day12-反射操作构造器(创建对象)

This commit is contained in:
2026-04-01 15:24:46 +08:00
parent 61801feaa8
commit 631909e68a
2 changed files with 110 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
package com.inmind.refelct02;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/*
反射操作构造器(创建对象)
Class Constructor<T>
总结:
构造器如何获取呢??
Class对象的2个API
getConstructor获取public的构造器
getDeclaredConstructor获取所有定义过的构造器
构造器的作用:创建对象
constructor.setAccessible(true);
Object o = constructor.newInstance("张三", 18);
*/
public class ConstructorDemo04 {
//普通的构造方法创建学生对象
public static void main(String[] args) {
Student student = new Student();
System.out.println(student);
}
//使用反射API来创建学生对象
@Test
public void method1() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//获取Class
Class<?> clazz = Class.forName("com.inmind.refelct02.Student");
//Class的newInstance()的功能:底层调用的就是指定类的无参构造方法,从而创建出对象
Object o = clazz.newInstance();
System.out.println(o instanceof Student);
System.out.println(o);
}
//获取无参构造方法对象(构造器),创建出学生对象
@Test
public void method2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class
Class<?> clazz = Class.forName("com.inmind.refelct02.Student");
/*
获取构造器对象
Constructor<?>[] getConstructors() 返回一个包含 Constructor对象的数组 Constructor对象反映了由该 Class对象表示的类的所有公共构造函数。
Constructor<T> getConstructor(Class<?>... parameterTypes) 返回一个 Constructor对象该对象反映由该 Class对象表示的类的指定公共构造函数。
*/
Constructor<?> constructor = clazz.getConstructor();
/*
通过指定构造器,创建出学生对象
public T newInstance(Object ... initargs),initargs就是对应构造器的参数如果有就传入
*/
Object o = constructor.newInstance();
System.out.println(o);
}
//获取私有满参构造方法对象(构造器),创建出学生对象
@Test
public void method3() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取Class
Class<?> clazz = Class.forName("com.inmind.refelct02.Student");
/*
获取满参的构造器对象
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 返回一个 Constructor对象。
*/
//getDeclaredConstructor:可以获取Class中定义的所有的构造方法包含私有构造方法
Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);
//暴力反射,修改对应构造器的访问权限
constructor.setAccessible(true);
/*
通过满参的构造器对象,创建出学生对象
public T newInstance(Object ... initargs),initargs就是对应构造器的参数如果有就传入
*/
Object o = constructor.newInstance("张三", 18);
System.out.println(o instanceof Student);
System.out.println(o);
}
}

View File

@@ -1,5 +1,35 @@
package com.inmind.refelct02;
public class Student {
//属性(成员变量)
String name;
int age;
//无参构造方法
public Student() {
}
//满参构造方法
private Student(String name, int age) {
this.name = name;
this.age = age;
}
//行为(成员方法)
public void show(){
System.out.println("无参无返回值的show方法执行了");
}
private int show(int i){
System.out.println("有参有返回值的show方法执行了");
return i+100;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}