Skip to content

Instantly share code, notes, and snippets.

@hotblac
Created May 27, 2023 09:11
Show Gist options
  • Save hotblac/36b9f6709da1026cb37dbc89ae038e30 to your computer and use it in GitHub Desktop.
Save hotblac/36b9f6709da1026cb37dbc89ae038e30 to your computer and use it in GitHub Desktop.
Classloaders and instanceof
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
public static void main(String[] args) throws Exception {
URL classLocation = new File("classes/").toURI().toURL();
try (URLClassLoader customClassLoader = new URLClassLoader(new URL[]{classLocation}, null)) {
ClassLoader applicationClassLoader = Main.class.getClassLoader();
Object instance1 = new MyCustomClass("42");
Object instance2 = applicationClassLoader.loadClass("MyCustomClass").getDeclaredConstructor(String.class).newInstance("42");
Object instance3 = customClassLoader.loadClass("MyCustomClass").getDeclaredConstructor(String.class).newInstance("42");
System.out.println("instance1 instanceof MyCustomClass: " + (instance1 instanceof MyCustomClass));
System.out.println("instance2 instanceof MyCustomClass: " + (instance2 instanceof MyCustomClass));
System.out.println("instance3 instanceof MyCustomClass: " + (instance3 instanceof MyCustomClass));
System.out.println("instance1.name(): " + safeGetName(instance1));
System.out.println("instance2.name(): " + safeGetName(instance2));
System.out.println("instance3.name(): " + safeGetName(instance3));
System.out.println("instance1.equals(instance2): " + instance1.equals(instance2));
System.out.println("instance1.equals(instance3): " + instance1.equals(instance3));
}
}
private static String safeGetName(Object o) {
try {
MyCustomClass myObj = (MyCustomClass) o;
return myObj.getName();
} catch (Exception e) {
return e.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment