Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to set the classpath through a java program ?

 
Vibhas Zanpure
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any proper way to do it ? In my engineering project, I am actually uploading .jar files or directories(which contain .class files).... After uploading a particular .jar/.class file from a directory path different than the original classpath, how do i invoke Reflection on it ?


My questions are ::

1) How to set classpath for a project/jar which we upload from a different directory at run time ?

2) Is there a way to invoke reflection of a .jar file just like we do it on a single .class file ?


Thanks
 
Campbell Ritchie
Sheriff
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

This part of the Java™ Tutorials tells you about jar files; you can add a classpath to a jar file, which the link describes.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the classes in the JAR file need to be dynamically loaded you should use a URLClassLoader. You can use file.toURI().toURL() for getting a URL from a File instance.
 
Vibhas Zanpure
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ ROB PRIME

I tried using that trick, but its not working. Thanks

Is there any way to set the class path of JVM through a program while you upload a .class file dynamically by selecting a .class file through a FileDialog.... ??

In my project, if I upload any .class file at runtime, a ClassNotFoundException is thrown by JRE if the class doesnt exist in the default classpath( i.e. the project folder)...

So how to fix this ???

Please help me, thanks.
 
Gopi Chella
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Vibhas

Like Rob said you should use URLClassLoader class and the method file.toURL(), Since the method is protected you need to use reflection to invoke it.

The reflection is necessary to access the protected method addURL.

 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also subclass it to make the method public. Something like this:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic