反射机制4(使用反射调用有参构造)

在之前所编写的代码实际上发现都默认使用了类中的无参构造方法,如果没有无参呢?那我们就要使用反射调用有参构造方法。

Class类里面有一个方法可以取得构造:
取得全部构造:
public Constructor<?>[] getConstructors()
throws SecurityException

取得一个指定参数顺序的构造:public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException

以上两个方法返回的都是java.lang.reflect.Constructor类对象。在这个类中提供有一个明确传递有参构造内容的实例化对象方法

public T newInstance(Object... initargs)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException

范例:调用有参构造方法

package TestDemo;

import java.lang.reflect.Constructor;

class Book{
    private String title;
    private double price;
    public Book(String title,double price){
        this.title=title;
        this.price=price;
    }

    @Override
    public String toString() {
        return "BookName:"+this.title+",price:"+this.price;
    }
}

public class TestDemo{
    
    public static void main(String[] args) throws Exception{
        Class<?> cls=Class.forName("TestDemo.Book");
        //这里的两个参数对应有参构造的两个类型Book(String title,double price)
        Constructor<?> con=cls.getConstructor(String.class,double.class);
        Object obj=con.newInstance("Java Developer",79.8);//有参构造实例化对象
        System.out.println(obj);
    }   
}

9003228-c96ed2ff7c5a5a91.png
image.png

调用有参构造如此麻烦,所以简单JavaBean的开发,之前一直强调至少保留有无参构造方法。

猜你喜欢

转载自blog.csdn.net/weixin_34150830/article/details/87040389