What is the Java equivalent of the general C # constraint "T, K: where is T: It <K>"?
What is the Java equivalent for this C # declaration?
public class AsyncThreadPool<T, K> where T : IAsyncThread<K> { and IAsyncThread is the interface
public interface IAsyncThread<T> { T GetAsyncUsedObject(); void StartAsyncRequest(); } I tried:
public class AsyncThreadPool<T extends IAsyncThread<K>, K > But itβs wrong, since T implements IAsyncThread<K> does not extend it.
And I need to use T.StartAsyncRequest() or similar in this class
In C #, this is:
T asyncThread = default(T); asyncThread.StartAsyncRequest() Your <T extends IAsyncThread<K>> correct. Despite the fact that the class itself implements, rather than extends, the terminology for the general definition extends. If you would like, you could use <T extends Object & IAsyncThread<K>> or <T extends Object, IAsyncThread<K>> , but that would be optional.
To create a member of type T, the only thing you have at your disposal is to use the factory object.
public class AsyncThreadPool<T extends IAsyncThread<K>, K> { private final AsyncThreadFactory<T> factory; public ASyncThreadPool(AsyncThreadFactory<T> factory) { this.factory = factory; } public void foo() { T t = factory.createDefault(); t.startAsyncRequest(); } } General restrictions in Java have only two options: extends and super , and in this case there is no difference between extension and implementation. Your method declaration code should work as is.
To create an instance, you will need to create a template in which you use the T class to create it. Since you cannot directly use T.class , you can create a factory, such as the one offered by corsiKa, if you need to reuse creation templates, or you can just pass the Class<T> to the constructor for your class and keep this instance around.
public class AsyncThreadPool<T extends IAsyncThread<K>, K>{ private final Class<T> clazz; public AsyncThreadPool(Class<T> clazz){ this.clazz = clazz; } public void Start() throws InstantiationException, IllegalAccessException{ T instance = clazz.newInstance(); instance.StartAsyncRequest(); } } It may also be important to note that in C # using default(T) for a class or interface will create a null reference, so your original example is incorrect.