I'm trying to play with thought to see if I can get to the point where I can enter the class name, and my application will load this class and instantiate it. After several attempts that I discovered, I could not just insert the class name in Class.forName() without its package name, so I got an attempt to get a list of all available packages that were loaded, and trying to load the type I type in with each name pack until he gets hit.
This is what I have so far:
BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String s = ""; do { ClassLoader clsldr = ClassLoader.getSystemClassLoader(); Package[] pkgs = Package.getPackages(); s = console.readLine(); if(s.equals(":exit")) { System.exit(0); } boolean classFound = false; Object loadedClass = null; String classname = ""; for (int i = 0; i < pkgs.length; i++) { Package package1 = pkgs[i]; try { classname = package1.getName().replace('/', '.') + "." + s; clsldr.loadClass(classname); loadedClass = Class.forName(classname); classFound = true; } catch(Exception e) { } } System.out.println("LOADED A CLASS!!!!"); System.out.println(classname); System.out.println(loadedClass); } while(s.length() == 0);
This floor works very weird. For example, when I enter “Object” at the prompt, it somehow manages to load sun.net.util.Object , but when I print the actual object, it prints class java.lang.Object . I get the same with String , as well as several other things that I typed. One interesting thing I tried was int - it loaded sun.net.util.int , and when I printed the object, it just returned null. Another thing happened when I tried Java :
Java LOADED A CLASS!!!! sun.net.util.Java null
Does anyone know what is going on here? Is there something special in the sun.net.util package that causes this? I don’t care that my code doesn’t work exactly the way I want, I just wanted to know what causes this strange behavior.
Java version:
java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b17) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
I am using the 64-bit version of Windows 8, if that matters.
Logan source share