我如何使用 getConstructor(params).newInstance(args)? [英] How do I use getConstructor(params).newInstance(args)?

查看:77
本文介绍了我如何使用 getConstructor(params).newInstance(args)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很可能是一个愚蠢的问题,但我是 Java 新手,所以...

This could well be a stupid question, but I'm new to Java, so...

我目前有一些目前正在使用的代码clazz.asSubclass(asSubclassOfClass).getConstructor().newInstance()

I've currently got some code where currently this is being used clazz.asSubclass(asSubclassOfClass).getConstructor().newInstance()

我需要将一些参数传递给构造函数,因此我想将其更改为:clazz.asSubclass(asSubclassOfClass).getConstructor(params).newInstance(args)

I need to pass some arguments to the contructort so I want to change it to: clazz.asSubclass(asSubclassOfClass).getConstructor(params).newInstance(args)

我不明白的是我需要作为 params 传入什么以及我需要作为 args 传入什么.

What I don't understand is what I need to pass in as params and what I need to pass in as args.

假设我想传入一个字符串howdy"和一些名为 XyzObj 的 XYZ 类型的对象.我该如何指定?我将什么作为参数传递,我将作为参数传递什么?

Let's say I wanted to pass in a String "howdy" and some object of type XYZ called XyzObj in. How would I specify that? WHat would I pass as params and what would I pass as args?

推荐答案

在 Java 中这被称为 反射.

In Java this is called Reflection.

假设这个类有这个构造函数,否则我相信你会得到一个 NoSuchMethod 异常.

Assuming the class has this constructor, otherwise you will get a NoSuchMethod exception I believe.

clazz.asSubclass(asSubclassOfClass)
    .getConstructor(String.class,XYZ.class)
    .newInstance("howdy",XyzObj);

由于您是 Java 新手,让我为您提供一个更简单的方法,以便您了解执行此操作时发生的事情.

Since you are new to Java, let me give you an easier so that you can understand what's going on under the hood when you do this.

假设您有以下类:

public class ParentClazz{
        String someVar;
    public ParentClazz(){
        someVar="test";
    }
    public ParentClazz(String someVar){
        System.out.println("I have been invoked");
        this.someVar=someVar;
    }
}

然后你有以下主要方法:

Then you have the following main method:

public static void main(String[] args) throws ParseException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
           ParentClazz.class.asSubclass(ParentClazz.class).getConstructor(String.class).newInstance("howdy");
    }

如果您运行它,您会注意到控制台输出打印消息 - 我已被调用.这意味着您使用反射调用了 ParentClazz 的构造函数.

If you run this you will notice the console output print message - I have been invoked. This means that using reflection you have invoked the constructor of ParentClazz.

如果场景允许您使用标准对象创建过程,您可以做同样的事情:

You can do the same thing if the scenario allows you is by using standard object creation process:

ParentClazz clazz = new ParentClazz("howdy");

希望这有助于您理解它.

Hope this helps you understand it.

这篇关于我如何使用 getConstructor(params).newInstance(args)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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