扩展类并实现接口的泛型类 [英] Generic class that extends class and implements interface
问题描述
public interface SomeInterface {
public void someMethod();
}
public class MyFragment extends Fragment implements SomeInterface {
// implementation
}
//这里是类,我需要创造。 T必须扩展Fragment并实现
// SomeInterface。但是,我担心,如果我直接使用MyFragment,它会从MyFragment创建一个
//依赖SomeClass。
public class SomeClass / * generic?* / {
public SomeClass(T parent);
}
是否有可能?
进一步,使用我的T类,我想创建视图,使用T.getActivity()作为上下文。
T必须扩展Fragment并实现SomeInterface
在这种情况下,您可以声明 SomeClass
如下:
public class SomeClass< T extends Fragment& SomeInterface>
这需要一个类型为 T
扩展 Fragment
并实现 SomeInterface
。
此外,使用我的T类,我想创建视图,使用T.getActivity()作为上下文。
我不熟悉Android,但是如果 getActivity()
是在 Fragment
中声明的公共实例方法,那么将会是完全可以在 T
的实例上调用它,因为编译器将知道所有的 T
必须继承该方法。
To reduce dependece of class, I want to send parameter (using generic class) to constructor that extends some class and implements interface, for example
public interface SomeInterface{
public void someMethod();
}
public class MyFragment extends Fragment implements SomeInterface{
//implementation
}
//here is classs, that I need to create. T must extend Fragment and implements
//SomeInterface. But, I'm afraid, if I'll use MyFragment directly, it will create a
//dependence of SomeClass from MyFragment.
public class SomeClass /*generic?*/ {
public SomeClass(T parent);
}
Is it possible?
Futher, using my T class, I want to create views, using T.getActivity() as Context.
T must extend Fragment and implement SomeInterface
In that case you could declare SomeClass
as the following:
public class SomeClass<T extends Fragment & SomeInterface>
That would require an object of type T
to both extend Fragment
and implement SomeInterface
.
Further, using my T class, I want to create views, using T.getActivity() as Context.
I'm unfamiliar with Android, but if getActivity()
is a public instance method declared in Fragment
then will be entirely possible to call it on an instance of T
, since the compiler will know all T
s must inherit that method.
这篇关于扩展类并实现接口的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!