比方說,我需要爲界,通用Comparable
類型的類:包封物仿製藥
class A<T extends Comparable<T>> {
// this is just an example of usage of T type
List<T> comparables;
int compareSomething(T smth) {
return comparables.get(0).compareTo(smth);
}
}
類有在簽名自己的泛型方法:
<V> Future<V> submit(Callable<V> task) {
return someExecutorService.submit(task);
}
現在,有限制submit
方法的輸入只接受Callables
也實現T
的可能性?我第一次嘗試這樣的:
<V, W extends T & Callable<V>> Future<V> submit(W task) {
if(compareSomething(task) != 0)
throw new RuntimeException("");
return someExecutorService.submit(task);
}
,但發現這是不可能的(原因描述here)。有沒有優雅的可能性繞過它?
編輯:一個醜陋可能性我能想到的是在兩種不同類型的分裂封裝,並通過在submit
對象對:
class A<T extends Comparable<T>> {
// this is just an example of usage of T type
List<T> comparables;
int compareSomething(T smth) {
return comparables.get(0).compareTo(smth);
}
<V> Future<V> submit(Callable<V> task, T comparable) {
if(compareSomething(comparable) != 0)
throw new RuntimeException("");
return someExecutorService.submit(task);
}
}
的主要缺點是,該方法簽名變得比較複雜,我也需要一段後者代碼有些人Callable
■一個一對一的映射T
秒。 ?也許我們可以認爲,解決它以適當的方式..
編輯模式,採取兩種:讓我來簡單解釋一下我想要實現的。我正在開發一個能夠執行某種特殊任務調度的自定義線程池實現。爲此,該服務只接受一種特殊的Callable
任務。這些Callable
■找實現自定義界面,類似於Comparable
之一。通過比較使用此界面中的方法的任務對,該服務將:
- 如果傳入任務被任何正在運行的任務阻塞,則阻止該傳入任務。
- 在完成任務的
Future
完成調用尚未完成的任務。 - 通過比較他們確定的待處理任務的執行順序。
阻擋/比較邏輯應該由任務本身來提供。這樣,線程池類應該只定義池對象正在接受什麼樣的特殊類型,它根本不關心它們是什麼類型的,它們的返回類型是什麼。
編輯,採取三種:基於Erick Robertson的answer,它現在能夠防止發臭任務提交:
public static void test(String[] args) {
A<Valid> scheduler = new A<>();
scheduler.betterSubmit(new Valid()); // applies to method signature
scheduler.betterSubmit(new Forbidden()); // rejected on compile time
scheduler.betterSubmit(new ConformWithValid()); // still appliable because all required interfaces implementations recognised
}
// just a bunch of test classes
private static class Valid implements Comparable<Valid>, Callable<Void> {
@Override
public int compareTo(Valid o) {
return 0;
}
@Override
public Void call() throws Exception {
return null;
}
}
private static class Forbidden implements Comparable<Forbidden>, Callable<Void> {
@Override
public int compareTo(Forbidden o) {
return -1;
}
@Override
public Void call() throws Exception {
return null;
}
}
private static class ConformWithValid implements Comparable<Valid>, Callable<Boolean> {
@Override
public int compareTo(Valid o) {
return 1;
}
@Override
public Boolean call() throws Exception {
return Boolean.FALSE;
}
}
尼斯和容易!希望有一天這能幫助和我一樣的人。 :-)
密切相關:?在多重限制的類型參數爲什麼我不能用一個類型參數(http://stackoverflow.com/q/197190 ) – 2014-09-29 09:44:43