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. 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.
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 .
Class revDemoClazz = Class.forName("com.ank.dynamicJarFileCreation.revDemo");
Object revDemoObj = revDemoClazz.newInstance();
Method reverseNumberMethod = revDemoClazz.getMethod("reverseNumber", Integer.class);
reverseNumberMethod.invoke(revDemoObj, 12345);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.