Reputation: 1582
When will two classes considered same? Like, is there something acting as the signature of a class? If so, what counts in the signature, package info, class name, etc? I'm asking this because I need to dynamically load a class and I always got a ClassNotFoundException
A bit more detail: I'm using Eclipse. I have an abstract class Panel
in my package com.example.project.sub1
. And a class Test
in package com.example.project.sub2
, which will call
ClassLoader loader = new URLClassLoader( new URL[]{new URL("file://" + path)}); /*the path is specified runtime and can be in a different directory other than working directory. It's the path to the parent directory of the class file I need to load. */ Class<Panel> panelClass = (Class<Panel>)loader.loadClass(className); //class name is runtime specified.
That compiles fine. Then I copied all the stuff in Panel.java
in a new directory and created a class MyPanel extends Panel
along with Panel.java
. That compiles fine too, but when I specify the path to my new MyPanel.class
, I always got a ClassNotFoundException
. Any idea where I'm wrong? Thanks.
EDIT: The stack trace:
java.lang.ClassNotFoundException: MyPanel at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at com.example.project.sub2 (Test.java:111) at java.lang.Thread.run(Thread.java:680)
Upvotes: 0
Views: 866
Reputation: 691655
If you want to dynamically load the class com.example.project.sub1.Panel
from a file URL, then this URL should refer to the directory containing the directory com
. From there, the ClassLoader will look for the class in a subdirectory path matching the package path. And the class name to pass is the fully qualified name: com.example.project.sub1.Panel
.
Also, loding the class MyPanel will return a Class<MyPanel>
, not a Class<Panel>
. You should use Class<? extends Panel>
as the type of the variable.
I'm not sure why you're dynamically loading classes though. The actual problem you're trying to solve is probably solvable in another way.
Upvotes: 1
Reputation: 262474
java.lang.ClassNotFoundException: MyPanel
The class is not called "MyPanel", it is "com.example.project.sub1.MyPanel".
It's the path to the parent directory of the class file I need to load.
Yes, that won't work. It needs to be the directory at the root of the package hierarchy, so not "/some/path/classes/com/example/project/sub1/", but "/some/path/classes"
Upvotes: 2