Unable to cast when using reflection in Java
Following Coobird's excellent answer yesterday, I'm having trouble getting reflection to work in Java. I'll post the classes first then go into detail.
StHandler.java
package ds; public interface StHandler {
public void read();
}
DiStHandler.java
package ds;
public class DiStHandler {
public void read() {
System.out.println("Hello world");
}
Server.java
package ds;
public class Server {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("ds.DiStHandler");
StHandler input = (StHandler) clazz.newInstance();
input.read();
}
catch(Exception e) {}
}
What I am trying to do: I have an interface StHandler, which at the moment I want to have a single method: read(). DiStHandler is an implementation class which is available from the classpath. I'm trying to call the read method from here.
The problem: On the line
StHandler input = (StHandler) clazz.newInstance();
I am receiving the error: ds.DiStHandler cannot be cast to ds.StHandler
I have been trying to debug this for nearly two hours now but for the life of me cannot work out what the problem is. The reason I don't have implements StHandler
in DiStHandl开发者_如何转开发er is because I'm creating DiStHandler in a separate project.
I would greatly appreciate any advice on this. Thanks very much in advance,
M
You can't cast DiStHandler
to StHandler
if DiStHandler
doesn't implement that interface. Reflection doesn't let you subvert the type system - everything must still be type-safe.
If DiStHandler
can't implement StHandler
, then you need something else which does, and which in turn calls DiStHandler
(i.e. an adapter class).
You write
The reason I don't have
DiStHandler implements StHandler
is because I'm creating DiStHandler in a separate project.
Even if StHandler
is in a different project you can still use this construct. Indeed it may be good design to split projects. If so you should look at tools such as maven for managing dependencies - your DiStHandler will depend on StHandler . Getting maven into your tool chain will pay back quickly in terms of modularity
精彩评论