0

I'm trying to write a decompiler for Java using reflection (all I need is the method signature information from a jar file passed in). I'm using a URLClassLoader to load classes from the jar file, and then pass that class on to my decompiler.

However, I've run into a problem. The jar I'm trying to read contains different versions of classes already loaded into my environment. So when I call

ClassLoader myClassLoader = URLClassLoader.newInstance(jars, null);
Class<?> classToDecompile = Class.forName(className, false, myClassLoader);

It returns not the class from my jar file, but the one that's already been loaded. Is there a way to load the class information for reflection only and get it from the jar passed in rather than from the JRE?

Edit:

The jar I'm trying to decompile contains classes in the java.lang package, which causes a security exception to be thrown:

java.lang.SecurityException: Prohibited package name: java.lang

Ed Marty
  • 39,590
  • 19
  • 103
  • 156
  • Well, it turns out I don't care too much about the java.* stuff being different than my current JRE, so I can just filter that out. – Ed Marty Jul 14 '11 at 22:09

2 Answers2

3

ClassLoader.loadClass(String, boolean) - which URLClassLoader inherits - first checks for a previously-loaded class, and then, not finding any, checks with the parent class loader. You could override that method to bypass the check for a previously-loaded class. Not sure if you'd have to bypass the parent.

Mind you, this would be an evil class loader; you probably shouldn't use it for anything else.

You might also try reading the jar yourself, getting the contents of the class file (the byte codes), and calling ClassLoader.defineClass(name, byte[], int, int) yourself, supplying a unique name for the class. I think that's a better idea, actually.

Ladlestein
  • 6,100
  • 2
  • 37
  • 49
0

Why wasting time when there is JAD? If you still want to achieve that you have to write your own class loader with child-first strategy.

Community
  • 1
  • 1
Michael-O
  • 18,123
  • 6
  • 55
  • 121