![](/img/trans.png)
[英]Method parameter must be obj of certain class that implements certain interface
[英]Want to know if a certain class implements an specific interface
我有一个程序要求用户输入String
,它应该是实现Message
接口的类的名称。
所有的Java类都在ist.ap.labs
包中
代码是这样的:
Class cl = null;
try {
cl = Class.forName(className);
} catch (ClassNotFoundException clnfe) {
System.out.println("Class not found!");
System.exit(1);
}
if (!cl.isAssignableFrom(ist.ap.labs.Message)) {
System.out.println("Class not implements Message!");
System.exit(1);
}
但是我总是收到一个错误消息,说cannot find a symbol:class labs
有什么帮助吗?
您必须引用类文字,而不仅仅是类名称:
if (!cl.isAssignableFrom(ist.ap.labs.Message.class)) { ... }
// ^ Here
编辑:而且,是的,乔恩·斯凯特(Jon Skeet)在评论中再次正确地指出了这一点:您必须交换cl
和ist.ap.labs.Message.class
来执行所需的测试。
你可以做这样的事情
Class<?>[] interfaces = Child.class.getInterfaces();
List list = Arrays.asList(interfaces);
if(list.contains(Interface.class)){
System.out.println("true....");
}
这将告诉您该类是否实现了接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.