Java:没有默认构造函数的类的newInstance [英] Java: newInstance of class that has no default constructor

查看:1218
本文介绍了Java:没有默认构造函数的类的newInstance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的学生的家庭作业建立一个自动测试框架(基于jUnit,但这不重要)。他们必须为一些类创建构造函数,并向它们添加一些方法。后来,通过我提供的测试功能,他们将检查他们是否走了。

I'm trying to build an automatic testing framework (based on jUnit, but that's no important) for my students' homework. They will have to create constructors for some classes and also add some methods to them. Later, with the testing functions I provide, they will check if they went alright.

我想要做的是,通过反射,创建一个我想测试的类的新实例。问题是,有时,没有默认构造函数。我不在乎,我想创建一个实例并自己初始化实例变量。有什么办法这样做吗?
对不起,如果以前被问过,但是我找不到任何答案。

What I want to do is, by reflection, create a new instance of some class I want to test. The problem is that, sometimes, there is no default constructor. I don't care about that, I want to create an instance and initialize the instance variables myself. Is there any way of doing this? I'm sorry if this has been asked before, but just I couldn't find any answer.

提前感谢。

推荐答案

调用 Class.getConstructor(),然后 Constructor.newInstance )传入适当的参数。示例代码:

Call Class.getConstructor() and then Constructor.newInstance() passing in the appropriate arguments. Sample code:

import java.lang.reflect.*;

public class Test {

    public Test(int x) {
        System.out.println("Constuctor called! x = " + x);
    }

    // Don't just declare "throws Exception" in real code!
    public static void main(String[] args) throws Exception {
        Class<Test> clazz = Test.class;
        Constructor<Test> ctor = clazz.getConstructor(int.class);
        Test instance = ctor.newInstance(5);           
    }
}

这篇关于Java:没有默认构造函数的类的newInstance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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