Java 测试对象是否实现接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/766106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if object implements interface
提问by sebastiangeiger
This has probably been asked before, but a quick search only brought up the same question asked for C#. See here.
之前可能已经问过这个问题,但快速搜索只会提出与 C# 相同的问题。看这里。
What I basically want to do is to check wether a given object implements a given interface.
我基本上想做的是检查给定的对象是否实现了给定的接口。
I kind of figured out a solution but this is just not comfortable enough to use it frequently in if or case statements and I was wondering wether Java does not have built-in solution.
我有点想出了一个解决方案,但这只是在 if 或 case 语句中经常使用它不够舒服,我想知道 Java 是否没有内置解决方案。
public static Boolean implementsInterface(Object object, Class interf){
for (Class c : object.getClass().getInterfaces()) {
if (c.equals(interf)) {
return true;
}
}
return false;
}
编辑:好的,感谢您的回答。尤其是 Damien Pollet 和 Noldorin,你们让我重新思考了我的设计,所以我不再测试接口了。
采纳答案by dfa
The instanceof
operator does the work in a NullPointerException
safe way. For example:
该instanceof
运营商确实在工作NullPointerException
安全的方式。例如:
if ("" instanceof java.io.Serializable) {
// it's true
}
yields true. Since:
产生真。自从:
if (null instanceof AnyType) {
// never reached
}
yields false, the instanceof
operator is null safe (the code you posted isn't).
产生错误,instanceof
运算符是空安全的(您发布的代码不是)。
instanceofis the built-in, compile-time safe alternative to Class#isInstance(Object)
instanceof是Class#isInstance(Object)的内置、编译时安全替代方案
回答by Luke Woodward
This should do:
这应该做:
public static boolean implementsInterface(Object object, Class interf){
return interf.isInstance(object);
}
For example,
例如,
java.io.Serializable.class.isInstance("a test string")
evaluates to true
.
评估为true
.
回答by Andreas Petersson
that was easy :
那很简单 :
interf.isInstance(object)
回答by Steve Kuo
I prefer instanceof
:
我更喜欢instanceof
:
if (obj instanceof SomeType) { ... }
which is much more common and readable than SomeType.isInstance(obj)
这比 SomeType.isInstance(obj)
回答by Rafa
If you want to test for interfaces:
如果要测试接口:
public List<myType> getElement(Class<?> clazz) {
List<myType> els = new ArrayList<myType>();
for (myType e: this.elements.values()) {
if (clazz.isAssignableFrom(e.getClass())) {
els.add(e);
}
}
return els;
}
}
clazz is an Interface and myType is a Type that you defined that may implement a number of interfaces. With this code you get only the types that implement a defined interface
clazz 是一个接口,而 myType 是您定义的可以实现多个接口的类型。使用此代码,您只能获得实现定义接口的类型
回答by ThePoltergeist
With Apache commons-lang ArrayUtils, see if the interface you require is contained in the interfaces of you object
使用Apache commons-lang ArrayUtils,查看你需要的接口是否包含在你对象的接口中
public static Boolean implementsInterface(Object object, Class interf){
return ArrayUtils.contains(object.getClass().getInterfaces(), interf);
}
回答by danny117
I had this problem tonight with android and after looking at the javadoc solutions I came up with this real working solution just for people like me that need a little more than a javadoc explanation.
今晚我在 android 上遇到了这个问题,在查看了 javadoc 解决方案后,我想出了这个真正可行的解决方案,只是为了像我这样需要的不仅仅是 javadoc 解释的人。
Here's a working example with an actual interface using android java. It checks the activity that called implemented the AboutDialogListener interface before attempting to cast the AboutDialogListener field.
这是一个使用 android java 的实际界面的工作示例。在尝试转换 AboutDialogListener 字段之前,它会检查调用实现了 AboutDialogListener 接口的活动。
public class About extends DialogFragment implements OnClickListener,
OnCheckedChangeListener {
public static final String FIRST_RUN_ABOUT = "com.gosylvester.bestrides.firstrunabout";
public interface AboutDialogListener {
void onFinishEditDialog(Boolean _Checked);
}
private AboutDialogListener adl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Activity a = this.getActivity();
if (AboutDialogListener.class.isInstance(a)) {
adl = (AboutDialogListener) a;
}
}
... Later I check if the field adl is !null before calling the interface
... 后来我在调用接口之前检查字段 adl 是否为 !null
@Override
public void onStop() {
super.onStop();
sharedPref.edit().putBoolean(About.FIRST_RUN_ABOUT, _Checked).commit();
// if there is an interface call it.
if (adl != null) {
adl.onFinishEditDialog(is_Checked());
}
}