本文翻译自:Creating an instance using the class name and calling constructor

Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor. 有没有一种方法可以给定类名称(动态)来创建特定类的实例,并将参数传递给其构造函数。

Something like: 就像是:

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

Where "MyAttributeValue" is an argument to the constructor of MyClass . 其中"MyAttributeValue"MyClass的构造函数的参数。


#1楼

参考:https://stackoom.com/question/PZTb/使用类名称创建实例并调用构造函数


#2楼

If class has only one empty constructor (like Activity or Fragment etc, android classes): 如果class只有一个空的构造函数(例如Activity或Fragment等,android类):

Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getConstructors()[0];

#3楼

when using (ie) getConstructor(String.lang) the constructor has to be declared public. 使用(即) getConstructor(String.lang) ,必须将构造方法声明为public。 Otherwise a NoSuchMethodException is thrown. 否则,将引发NoSuchMethodException

if you want to access a non-public constructor you have to use instead (ie) getDeclaredConstructor(String.lang) . 如果要访问非公共构造函数 ,则必须使用getDeclaredConstructor(String.lang)代替。


#4楼

You can also invoke methods inside the created object. 您也可以在创建的对象内调用方法。

You can create object instant by invoking the first constractor and then invoke the first method in the created object. 您可以通过调用第一个承包商然后在创建的对象中调用第一个方法来立即创建对象。

    Class<?> c = Class.forName("mypackage.MyClass");Constructor<?> ctor = c.getConstructors()[0];Object object=ctor.newInstance(new Object[]{"ContstractorArgs"});c.getDeclaredMethods()[0].invoke(object,Object... MethodArgs);

#5楼

Another helpful answer. 另一个有用的答案。 How do I use getConstructor(params).newInstance(args)? 如何使用getConstructor(params).newInstance(args)?

return Class.forName(**complete classname**).getConstructor(**here pass parameters passed in constructor**).newInstance(**here pass arguments**);

In my case, my class's constructor takes Webdriver as parameter, so used below code: 就我而言,我的类的构造函数将Webdriver作为参数,因此在以下代码中使用:

return Class.forName("com.page.BillablePage").getConstructor(WebDriver.class).newInstance(this.driver);

#6楼

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing: 使用Class<?>在Java中创建对象的非常简单的方法,并传递构造函数参数:

Case 1:- Here, is a small code in this Main class: 情况1:-这是此Main类中的一小段代码:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;public class Main {public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {// Get class name as string.String myClassName = Base.class.getName();// Create class of type Base.Class<?> myClass = Class.forName(myClassName);// Create constructor call with argument types.Constructor<?> ctr = myClass.getConstructor(String.class);// Finally create object of type Base and pass data to constructor.String arg1 = "My User Data";Object object = ctr.newInstance(new Object[] { arg1 });// Type-cast and access the data from class Base.Base base = (Base)object;System.out.println(base.data);}}

And, here is the Base class structure: 并且,这是Base类结构:

public class Base {public String data = null;public Base() {data = "default";System.out.println("Base()");}public Base(String arg1) {data = arg1;System.out.println("Base("+arg1+")");}}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. 情况2:您可以为具有多个参数的构造函数类似地编写代码,并复制构造函数。 For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as: 例如,将3个参数作为参数传递给Base构造函数将需要在类中创建该构造函数,并且上面的代码更改如下:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" });

And here the Base class should somehow look like: 在这里,基类应该以某种方式看起来像:

public class Base {public Base(String a, String b, String c){// This constructor need to be created in this case.}
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code. 注意:- 不要忘记处理代码中需要处理的各种异常。

使用类名称创建实例并调用构造函数相关推荐

  1. 27、Python 面向对象(创建类、创建实例对象、访问属性、内置类属性、对象销毁、类的继承、方法重写、基础重载方法、运算符重载、类属性与方法、下划线双下划线)

    27Python面向对象(Python2) Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的.本章节我们将详细介绍Python的面向对象编程. ...

  2. Python之定义类并创建实例(一)

    在Python中,类通过 class 关键字定义.以 Person 为例,定义一个Person类如下: class Person(object):pass 类名以大写字母开头(如Person)并且如果 ...

  3. python中编完类后到实例编写_[零基础学python]编写类之一创建实例

    虽然已经对类有了一点点模糊概念,但是,阅读前面一讲的内容的确感到累呀,都是文字,连代码都没有. 本讲就要简单多了,尝试走一个类的流程. 说明:关于类的这部分,我参考了<Learning Pyth ...

  4. python创建实例会调用哪些魔术方法_Python最会变魔术的魔术方法,我觉得是它!...

    作者:豌豆花下猫 来源:Python猫 在,我有一个核心的发现:Python 内置类型的特殊方法(含魔术方法与其它方法)由 C 语言独立实现,在 Python 层面不存在调用关系. 但是,文中也提到了 ...

  5. Python基础学习——面向对象编程(第一讲:面向对象概述、面向对象三个基本特征(封装性、继承性、多态性)、类和对象(定义类、创建和使用对象、实例变量、类变量、构造方法、实例方法、类方法、静态方法))

    面向对象是Python最重要的特性,在Python中一切数据类型都是面向对象的. 1.面向对象概述 面向对象的编程思想是,按照真实世界客观事物的自然规律进行分析,客观世界中存在什么样的实体,构建软件系 ...

  6. Python 入门 —— Python 面向对象:类的创建及其基本内置方法的使用

    Python 面向对象:类的创建及其基本内置方法的使用 首先了解一下什么是面向对象 面向过程: 就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了. ...

  7. Python定义类、创建类的对象(类的实例化)

    定义类 语法格式 在python中,可以通过class关键字定义类,然后通过定义的类来创建实例对象.语法格式如下: calss 类名:类体 注意事项 在python中使用class关键字来定义类,定义 ...

  8. python 元类 type_Python 使用元类type创建类对象常见应用详解

    本文实例讲述了Python 使用元类type创建类对象.分享给大家供大家参考,具体如下: type("123") 可以查看变量的类型;同时 type("类名", ...

  9. React 16 Jest ES6 Class Mocks(使用ES6语法类的模拟) 实例三、四

    转载地址 React 16 Jest ES6 Class Mocks(使用ES6语法类的模拟) 实例三.四 项目初始化 git clone https://github.com/durban89/we ...

最新文章

  1. 图像集存储成MNIST数据集格式实现
  2. zuul 启动 threw exception_SpringCloud-Zuul-网关路由过滤器
  3. linux c下输入密码不回显
  4. iOS之 NSTimer(一)
  5. ubuntu 12.04及12.10无法安装 ia32-libs
  6. SpringBoot非官方教程 | 第二十六篇: sprinboot整合elk,搭建实时日志平台
  7. 计算机二级mysql模拟_2017年计算机二级MySQL考前模拟练习
  8. SQLHelper帮助类
  9. python安装失败无法访问_错误:由于环境错误而无法安装包错误:[WinError 5]访问被拒绝:...
  10. CSDN博客如何显示空白符
  11. 计算图层面积(针对于面要素)ArcObject c++
  12. opencv自然背景下交通标志形状分类c++代码_前端革命时刻:前端代码是怎样智能生成的-图像分离篇
  13. Scala,一门「特立独行」的语言!
  14. mysql 物理删除 索引_MySQL 索引重建
  15. python求职网站_Python 求职 Top10 城市,来看看是否有你所在的城市
  16. ASP.NET 参数传递,长度限制,及使用注意事项。
  17. python免费自学爬虫_看这里!免费python网络爬虫一站通
  18. 电商项目5:商品模块
  19. 刚刚,10位青年学者获得阿里达摩院青橙奖,钟南山寄语,每人100万,最小获奖者28岁
  20. php手机投屏功能,电脑手机投屏怎么操作设置?

热门文章

  1. php将汉字转换为拼音和得到词语首字母(一)
  2. 网站开发流程以及HTML5简介(七)
  3. html5,表单与label标签的用法2
  4. oracle 新手注意事项
  5. 活着是一种罪过,是上帝对你的另一种眷顾,叫做惩罚!活着痛苦!
  6. SpringMVC中异常捕获
  7. UEFI+GPT安装Win10和RHEL6.5双系统
  8. POJ 2392 Space Elevator(多重背包变形)
  9. 让系统在内存中高速运行
  10. zabbix监控tomcat服务