path and classpath

How to Add A Jar File To Java System Classpath At Run-time

Post Views: 2 This can be done by using a simple reflection API hack as demonstrated in below sample code. This example assumes you have a file “c:/Sample.txt” that is not already in class path and at run-time c:/ is added the System classpath and then Sample.txt is made available. import; import; import java.lang.reflect.Method; import; import;   public class HackJavaClasspath {   public static void addURL(URL url) throws Exception { URLClassLoader cl = (URLClassLoader) ClassLoader .getSystemClassLoader(); Class clazz = URLClassLoader.class;   Method method = clazz.getDeclaredMethod(“addURL”, new Class[] { URL.class }); method.setAccessible(true); method.invoke(cl, new Object[] { url }); }   public static void main(String[] args) throws Exception { //Add c: to the classpath addURL(new File(“c:/”).toURI().toURL()); //Now load the file from new location InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream(“Sample.txt”); System.out.println(in.available());   } } Running…

Read More

Why calling System.setProperty() does not affect the classpath at run-time

Post Views: 2 You can easily set any system properties in java using System.setPropoerty method, However it may not have any effect in case of CLASSPATH property. This is mainly because the Java system class loader is initialized very early in the JVM startup sequence. The class loader copies the classpath into its own data structures, and the classpath property is not read again. Therefore changing it after its already copied does not affect anything. There are mainly two reasons…

Read More

How to find the load location of a Java class file at run-time

Post Views: 2 There are two ways to find it: Using Classloader Below code snippet can be used to find the location of java class com.fromdev.MyClass this.getClass().getClassLoader().getResource(“com/fromdev/MyClass.class”)   Using Protection Domain We can use this to find the exact location a jar file containing the class JVM is using clazz.getProtectionDomain().getCodeSource().getLocation() How Java handles Two classes with same name in classpath If I have two classes with same name say in two different jar in my classpath which one will…

Read More