可以从我以前的问题找到这个问题的背景。从类的类型转换为引用类
上一页问题:http://tinyurl.com/chq4w7t
我有一个发送功能的接口Comm
:
public interface Comm
{
public int send(Socket socket, byte[] bytes);
}
我具有各种类(Server
,Client
,Serial
等),其实现了接口Comm
。我可以将这些类对象作为参数传递给另一个类中的另一个发送函数,该函数充当对象和各种插件之间的管理器,这些插件可配置为使用这些类中的一个作为通信媒介。
(Server
,Client
,Serial
等)作为参数传递给发送功能如下
public void Send(Comm com, Socket socket, byte[] message)
{
com.send(null, message);
}
从我刚才的问题我有一个getClasses
函数返回一个Class[]
并接受一个字符串参数。这用于提供不同的配置选项。
例如,我使用Class.forName("Client");
为客户端返回一个Class
对象。
现在终于我的问题是:
如何从Class
转换为Comm
类型?我为你下面试图得到一个想法:(cboxComm
是检验我的代码测试组合框它包含了Comm
对象的类名)
// Some code I have no idea how it works, an explanation would be awesome
// regarding the diamond syntax
Class<? extends Comm> classComm = Class.forName(cboxComm.getSelectedItem().toString());
// Error here, I don't know how to convert or cast it
Comm com = classComm;
// Sending function as described above
send(com, null, null);
'Comm com =(Comm)classComm;'这不工作吗?你应该有一个instanceof检查。 – Ankit
@Ankit:我当然不会指望它! –
您对“钻石语法”的评论没有多大意义 - 您没有使用钻石语法。 –