如何使用反射在构造函数中创建具有参数的类的实例? [英] How to create instance of a class with the parameters in the constructor using reflection?

查看:198
本文介绍了如何使用反射在构造函数中创建具有参数的类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

public class Test {

    public static void main(String[] args) throws Exception {
        Car c= (Car) Class.forName("Car").newInstance();
        System.out.println(c.getName());
    }
}

class Car {
    String name = "Default Car";
    String getName(){return this.name;}
}



clear code.

但是,如果我用params添加构造函数,一些像这样:

But, if I add constructor with params, some like this:

public Car(String name)
{this.name = name;}

我看到: java.lang.InstantiationException

因此,我不知道,

请帮助。

推荐答案

Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");

这篇关于如何使用反射在构造函数中创建具有参数的类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆