Why is my reflection loading weird classes?
I'm trying to play with reflection to see if I can get to a point where
I'm able to type in a class name and my application will load that class
and create an instance of it. After a few attempts I found I couldn't just
stick a class name in Class.forName() without its package name, so I wound
up trying to get a list of all available packages that have been loaded
and trying to load the class I type in with each package name till it gets
a hit.
This is what I've got 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);
It semi works in a very weird way. For example when I type in "Object" at
the prompt it somehow manages to load sun.net.util.Object, but when I
print out the actual object it prints class java.lang.Object. I get the
same thing with a String as well as several other things I typed. One
interesting one I tried was int - it loaded sun.net.util.int and when I
printed the object it just returned null.
Does anyone have any clue what's happening here? Is there something
special about the sun.net.util package that's causing this? I don't really
care that my code doesn't work exactly like I want, I would just love to
know what's causing this strange behaviour.
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'm on Windows 8 64 bit if that makes any difference.
No comments:
Post a Comment