![](/img/trans.png)
[英]Bound mismatch error on generics type argument for a generic class that extends another generic class
[英]Can a Java argument be type-bound by a Class contained in another object?
注意:這個問題主要是理論上的; 從那以后,我就放棄了立即使用它,因為我想過的所有事情都使我的代碼過於復雜,並且聞起來有點像反模式。 但是,我認為它在理論上很有趣,並且希望社區對此提供幫助。
我正在整理一些世紀之交編寫的用於圖像處理的代碼; 首先將具有很多冗余的單個類切分成多個BiFunction過濾器。 它們每個接受一個BufferedImage和一個強度(Double),然后返回一個新的BufferedImage。 當然,這些圖像濾鏡中的許多還有其他問題,例如效應半徑或其他強度,如果我要高效地鏈接它們,我希望能夠將它們設置為“均勻”(或准)。 -常數)。
我當前的方法只是簡單地進一步擴展ImageFilter類,並將統一設置為Bean樣式的屬性。 我最初想做的是將它們約束為一個通用類,該類保存在一個接口中,並且具有以下特點:
public void addProperty(Uniform<T> property, T type)
在這里,T完全由Uniform指定。
原始的類將所有這些制服按String名稱保留在HashMap中,但這是許多不良習慣的開始,每次我看到它時,我都會對其進行清理。 如果拼寫錯誤導致代碼失誤,那是不負責任的代碼。 我寧願像長大成人一樣只在那兒使用Singleton。
因此,總而言之,在Java中是否可以將參數類型綁定到另一個參數的泛型? 如果是這樣,怎么辦? 如果不是,是否有人知道將來有任何以這種方式擴展Java泛型的計划?
感謝您的輸入!
是的,我們可能要做的就是在方法本身上定義type參數。 檢查下面的示例。
公共類制服{
}
public class ImageFilter {
//store in a list which can store any type of Uniform
List<Uniform<?>> uniformList = new ArrayList<Uniform<?>>();
//store in a map which can store any type of uniform and uses type as key
Map<Class<?>, Uniform<?>> uniformMap = new HashMap<>();
//Type parameter 'T' on the method itself
public <T> void addProperty(Uniform<T> property, T type) {
uniformList.add(property);
uniformMap.put(type.getClass(), property);
}
}
{
//sample usage
new ImageFilter().addProperty(new Uniform<>(), "test");
new ImageFilter().addProperty(new Uniform<>(), new Double(2.0));
}
以下是示例用法
new ImageFilter().addProperty(new Uniform<>(), "test");
//or
new ImageFilter().addProperty(new Uniform<String>(), "test");
//if for some reason JVM can't infer the type itself, it can be set manually
new ImageFilter().<String>addProperty(new Uniform<String>(), "test");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.