Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 260
  • Last Modified:

Get a class from a jar gievn the className

Hi Experts,
I need to create a method that  returns a class<?>  from a jarFile given a className :
Class<?>  getClassFromJar (JarFile jar, className){
      Return the Class / Null if not found
}
e.g.
Class<?> clazz = getClassFromJAr ( MyBundle.jar, “org.kal.os.factory.class”);
0
bachra04
Asked:
bachra04
  • 7
  • 2
1 Solution
 
for_yanCommented:
You mean that this jar is not in your classpath ?

Otherwise you could use Class.forName(...)
0
 
for_yanCommented:
0
 
bachra04Author Commented:
Sorry not to be clear, the jar contains multiple classes including className

So the method will extract all classes and if the class

matches the given className, it returns it.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
for_yanCommented:
This is how you can do it with JCL:

JarClassLoader jcl = new JarClassLoader();

  //Loading classes from different sources
  jcl.add("myjar.jar");
  jcl.add(new URL("http://myserver.com/myjar.jar"));
  jcl.add(new FileInputStream("myotherjar.jar"));
  jcl.add("myclassfolder/");

  //Recursively load all jar files in the folder/sub-folder(s)
  jcl.add("myjarlib/");

  JclObjectFactory factory = JclObjectFactory.getInstance();

  //Create object of loaded class
  Object obj = factory.create(jcl, "mypack.MyClass");

Open in new window

0
 
for_yanCommented:


So do you need this class for using it in the same code after you extract it?
Or you just need to extract it as a file?
0
 
for_yanCommented:
If you need to use it in your code then
the above snippet from JCL shows how to create instance of such class
0
 
bachra04Author Commented:
I need to extract it as a file
0
 
for_yanCommented:
To extract as a file - jar is just a zip file - so
the same way you extract it from zip file should work
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now