简体   繁体   English

我可以将对象转换为具有接口的类吗?

[英]Can I cast an object to class with interface(s)?

I have a object obj and I want to cast it to View that implements interface Tool . 我有一个对象obj ,我想将其View为实现接口Tool View

class Whatever {
    View viewObj;
    Tool toolObj;
    ...
    public void setViewTool( View obj )
    {
        viewObj = obj;
        toolObj = (Tool) obj;
    }

    ...
}

I want to avoid creating two objects to handle the situation or using one that I have to cast each time I want to call an implemented method of View or Tool. 我想避免创建两个对象来处理这种情况,或者避免每次调用视图或工具的实现方法时都要使用一个对象。

The same thing, if possible, when using two interfaces or more. 如果使用两个或更多个接口,则可能是同一件事。 I recall a language I could do something like this View<Tool, and, others, interfaces> . 我记得一种语言,我可以做类似View<Tool, and, others, interfaces>


Example

I think the title and the first line of the question is clear. 我认为问题的标题和第一行很明确。 But, may it's not. 但是,可能不是。

I have three tools to show in the app. 我有三个工具可以在应用程序中显示。 One is made extending LinearLayout, and the others two, FrameLayout. 一种是扩展LinearLayout,另一种是FrameLayout。 These view objects has to implements Tool interface because there are methods called when it inits, finishes and when the user do some gestures. 这些视图对象必须实现Tool接口,因为在其初始化,完成以及用户执行某些手势时会调用一些方法。 But, it's a view too, and when I need to show, it needs to call things like setLayout, addView, animate . 但是,它也是一个视图,当我需要显示时,它需要调用诸如setLayout, addView, animate类的东西。

Just to clarify, it's works fine in the example above. 为了澄清起见,在上面的示例中它工作正常。 But I have to set two variables to handle the same object, one for doing stuff related to the view aspect, and one to the Tool interface. 但是我必须设置两个变量来处理同一个对象,一个用于执行与视图方面相关的工作,另一个用于Tool接口。

I can't say generic class doesn't work but the way I have tried, it doesn't. 我不能说通用类不起作用,但是我尝试过的方法却没有。 What I wish, was the possibility of create a class property as private (View implements Tool) myObj; 我希望可以将类属性创建为private (View implements Tool) myObj; .

Now, I almost sure it's not possible from this other answer: Java - Defining a member that extends class A and implements interface B 现在,我几乎可以肯定,从另一个答案中不可能: Java-定义扩展类A和实现接口B的成员

If your question is 如果你的问题是

I know I can cast an object (A) to another (B), but can I do it if the B class implement an interface (C) ? 我知道我可以将一个对象(A)转换为另一个(B),但是如果B类实现接口(C)可以实现吗?

Then the answer is yes. 那么答案是肯定的。 It does not change anything that the class B implement C or not. 它不会改变类B是否实现C的任何内容。 But as for any object cast you can do it only if the instance a of A is also an instance of B. You can test it like that : 但是对于任何对象强制转换,只有当A的实例a也是B的实例时,您才能这样做。您可以像这样测试它:

A a = new A()
if(a instanceof B) {
    //a is an instance of B
}

If the instance a of A is also an instance of B it means that it implements C. So you can do 如果A的实例a也是B的实例,则意味着它实现了C。因此,您可以执行

C c = (C) a;
B b = (B) a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM