Java ReflectionFactory

xiaoxiao2025-10-10  4

不用构造器实例化一个对象

package com.example.demo.controller; import sun.reflect.ReflectionFactory; import java.lang.reflect.Constructor; public class Test { private String id; private String name; private Test() { System.out.println("test 1"); } private Test(String id, String name) { this.id = id; this.name = name; System.out.println("test 2"); } public static void main(String[] args) throws Exception { ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory(); Constructor<?> constructor = reflectionFactory.newConstructorForSerialization(Test.class, Object.class.getDeclaredConstructor()); constructor.setAccessible(true); Object instance = constructor.newInstance(); System.out.println(instance.getClass().getName()); } }

运行结果

com.example.demo.controller.Test

可以看到并没有输出 “test 1” or “test 2”,说明其并不是通过构造器创建的对象。 实现原理暂时不清楚

转载请注明原文地址: https://www.6miu.com/read-5037659.html

最新回复(0)