Controlled interface Implementation
In Serialization, the class which we want to be serialized has to implement the Serializable interface, otherwise a NotSerializableException is thrown. There are many other examples like that in the various features of Java. Now I just want to know how to bring in such control in custom classes and interfaces. I have an interface called Agent. There can be many different types of Agents, al开发者_高级运维l of them must implement the Agent interface. I also have a class called Node. Nodes create Agents. Now how to bring in control in such a situation, such that an agent always much implement Agent interface, otherwise an exception will be thrown. I might sound a bit vague, but if someone can provide me with the general idea, then I can provide further details if necessary.
If you have a Node method which must take an Agent, you specify that the argument has to be an Agent.
interface Node {
void method(Agent agent); // must be an Agent.
Agent returnAgent(); // must return an Agent.
}
Serialization is a special case. This is because not all types which are serializable are Serializable. Built in types like int[] is serializable but doesn't implement Serializable. This type of check cannot be done by the compiler and can only be done at runtime.
You could check to see if the Agent implements the interface before your Node creates the Agent.
public class CheckForInterface
{
public static void main(String[] args) throws ClassNotFoundException
{
Class cl = (Class)Class.forName("TestImpl");
Class[] itfs = cl.getInterfaces();
for(Class c : itfs)
{
System.out.println(c);
}
}
}
import java.io.Serializable;
public class TestImpl implements Serializable
{
public TestImpl()
{
}
}
This outputs: interface java.io.Serializable
精彩评论