[英]How to create dynamic jar file to get access of multiple classes and its methods from an entry point(main) without importing in java?
I want to access one or many classes from an entry point(main) without importing package. 我想从入口点(主)访问一个或多个类而不导入包。 For example: 例如:
package com.ank.dynamicJarFileCreation;
public class revDemo {
public static int reverseNumber(int n)
{
int rem,rev=0;
while(n>0)
{
rem=n%10;
rev=rev*10 + rem;
n=n/10;
}
return rev;
}
}
above one is revDemo
class and I want to access above reverseNumber(int n)
method from an entry point below. 上面是revDemo
类,我想从下面的入口点访问上面的reverseNumber(int n)
方法。 For example: 例如:
public class revCall {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
int n=485154;
System.out.println(revDemo.reverseNumber(n));
Or by this way. 或者通过这种方式。
Class cls = Class.forName("reverseDemo");
Object obj = cls.newInstance();
System.out.print("Class Name"+cls.getName());
Object obj = null; //It is a object of -> com.ank.dynamicJarFileCreationo
System.out.println(((com.ank.dynamicJarFileCreation)obj).reverseNumber(n));
}
}
You are very near to your own solution. 您非常接近自己的解决方案。 Actually you created the instance of your required class dynamically using Class.forName() and newInstance() functions. 实际上,您是使用Class.forName()和newInstance()函数动态创建所需类的实例的。
Next step is to get the Function from the Class by the name of method, say reverseNumber and execute the same using created instance of revDemo . 下一步是通过方法名称(例如reverseNumber)从Class中获取Function,并使用创建的revDemo实例执行该功能。
Class revDemoClazz = Class.forName("com.ank.dynamicJarFileCreation.revDemo");
Object revDemoObj = revDemoClazz.newInstance();
Method reverseNumberMethod = revDemoClazz.getMethod("reverseNumber", Integer.class);
reverseNumberMethod.invoke(revDemoObj, 12345);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.