简体   繁体   English

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

[英]Creating an instance using the class name and calling function

How to create an instance of a particular class with class name (dynamic) and pass parameters to it's a function of class? 如何使用类名(动态)创建特定类的实例并将参数传递给它是类的功能?

my pseudo code is : 我的伪代码是:

String className = "login";
Class<?> clazz = Class.forName(className);
clazz.checkUserFunc(argument);

checkUserFunc Function is member of Login class checkUserFunc函数是Login类的成员

You can get an instance of the class constructor matching the give arguments with getConstructor . 您可以获得与getConstructor参数匹配的类构造函数的实例。

Constructor<?> ctor=thisClass.getConstructor(<arguments>); // where arguments are the parameters expected by the constructor.

You can then create an instance of the class and call whatever methods you like with getDeclaredMethod . 然后,您可以创建该类的实例,并使用getDeclaredMethod调用所需的任何方法。

getDeclaredMethod(String name, Class...<?> parameterTypes)

First, you have to create a new instance of your class: 首先,您必须创建类的新实例:

Object o = clazz.newInstance();

Note: If your class does not have a default constructor, newInstance() will throw an exception. 注意:如果您的类没有默认的构造函数,则newInstance()将引发异常。 In that case, you must query the appropriate constructor from your class and call it. 在这种情况下,您必须从类中查询适当的构造函数并调用它。 This only makes sense, if you have some kind of convention, eg the constructor must accept exactly on String argument or so (see Creating an instance using the class name and calling constructor ). 仅当您具有某种约定时才有意义,例如,构造函数必须完全接受String参数 (请参阅使用类名创建实例并调用构造函数 )。 The easiest way is to require a default constructor, so the code above will work. 最简单的方法是需要一个默认的构造函数,因此上面的代码将起作用。

Then you can call any instance method of your object. 然后,您可以调用对象的任何实例方法。 Usually you should have another convention like the class must implement interface MyInterface . 通常,您应该有另一个约定,例如该类必须实现接口MyInterface This makes calling your method easy: 这使调用您的方法变得容易:

MyInterface myObj = (MyInterface)o;
myObj.checkUserFunc(argument);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM