使用类名和调用构造函数创建实例

编程入门 行业动态 更新时间:2024-10-27 18:21:52
本文介绍了使用类名和调用构造函数创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法根据类名(动态)创建特定类的实例并将参数传递给其构造函数.

Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.

类似于:

Object object = createInstance("mypackage.MyClass","MyAttributeValue");

其中 "MyAttributeValue" 是 MyClass 的构造函数的参数.

Where "MyAttributeValue" is an argument to the constructor of MyClass.

推荐答案

是的,例如:

Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(String.class); Object object = ctor.newInstance(new Object[] { ctorArgument });

这当然只适用于单个字符串参数,但您可以很容易地修改它.

That will only work for a single string parameter of course, but you can modify it pretty easily.

请注意,类名必须是完全限定的,即包括命名空间.对于嵌套类,您需要使用美元(因为这是编译器使用的).例如:

Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, you need to use a dollar (as that's what the compiler uses). For example:

package foo; public class Outer { public static class Nested {} }

要为此获得 Class 对象,您需要 Class.forName("foo.Outer$Nested").

To obtain the Class object for that, you'd need Class.forName("foo.Outer$Nested").

更多推荐

使用类名和调用构造函数创建实例

本文发布于:2023-11-11 23:56:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!