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

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

问题描述

我正在尝试为我的学生的作业构建一个自动测试框架(基于 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:没有默认构造函数的类的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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