【‘newInstance()‘ 已经过时了】
问题:‘newInstance()’ 已经过时了
User user = (User) class1.newInstance();
原因:jdk9 之后,对newInstance()做了些改变(截取了参数说明)
* @param initargs array of objects to be passed as arguments to
* the constructor call; values of primitive types are wrapped in
* a wrapper object of the appropriate type (e.g. a {
@code float}
* in a {
@link java.lang.Float Float})
*
* @return a new object created by calling the constructor
* this object represents
*
@CallerSensitive
@ForceInline // to ensure Reflection.getCallerClass optimization
public T newInstance(Object ... initargs)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
解决:当前版本jdk11
package com.example.demomain.reflectstudy;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class GetInstance {
/*
* 调用运行时类的构造器:
* */
@Test
public void testConstructor() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
//获取指定参数为String的构造器
Constructor constructor1 = User.class.getDeclaredConstructor(String.class);
//2.保证此构造器是可访问的
constructor1.setAccessible(true);
//3.调用此构造器创建运行时类的对象
//方法一:jdk9之前
//User user = (User)clazz.newInstance();
//方法二:jdk9之后: 参数为 Constructor 指定的构造参数
User user = (User) constructor1.newInstance("lfsun");
user.print();
//获取指定无参构造器
Constructor constructor2 = User.class.getDeclaredConstructor();
constructor2.setAccessible(true);
User user1 = (User) constructor2.newInstance();
// 引用类型默认为 null
user1.print();
}
}
涉及到的实体类:
package com.example.demomain.reflectstudy;
/**
* @author lfsun
*/
public class User {
private String userName;
User(String userName) {
this.userName = userName;
}
User() {
}
public void print() {
System.out.println("Hello World " + userName);
}
}
还没有评论,来说两句吧...