[英]How to call a method in another class when the given classname is string
I have two classes in java.我在java中有两个类。 I am calling a method of 2nd class from 1st class when the 2nd class name is stored in a string variable.当第二类名称存储在字符串变量中时,我正在从第一类调用第二类的方法。 I tried the below code.It creates the class.我尝试了下面的代码。它创建了类。
String adapterClass = "com.appzillon.server.impl.ViewAccDtlsAdapterImpl";
Class className = Class.forName(adapterClass);
After that how to call the method.Method name is getInfo
with a string type paramater.之后如何调用方法。方法名称是getInfo
,带有字符串类型参数。
Method method = className.getDeclaredMethod("getInfo", String.class);
method.invoke(instance, "your parameter");
Where instance
is either:其中instance
是:
Object instance = null;
if the method is static.如果方法是静态的。 Or:或者:
Object instance = className.getDeclaredConstructor().newInstance();
If the method is a member method如果方法是成员方法
For scenarios like these, you can very well use Java Reflection APIs.对于此类场景,您可以很好地使用 Java 反射 API。 Class classInstance = Class.forName(<your class name>); Methoed methodHandle = classInstance.getMethod(<methodName>,<arguments classes>); Object returnValue = methodHandle.invoke(null, "parameter-value1");
Note : The null parameter is the object you want to invoke the method on.注意:null 参数是您要对其调用方法的对象。 If the method is static you supply null instead of an object instance如果该方法是静态的,则提供 null 而不是对象实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.