[英]Java call a method on sibling classes
美好的一天,
我嘗試了良好的google搜索,甚至閱讀了一些內容,但不確定如何進行。 這是問題所在:
當我打電話duplicate()
上java.nio.Buffer中的任何實現,我曾與原來的緩沖區設置的字節順序buf.order(ByteOrder.LITTLE_ENDIAN)
不保留。 這是個問題。 因此,我着手創建一個靜態方法,該方法使我可以像以下示例一樣執行以下操作:
public static ByteBuffer endianPreservingDuplicate(ByteBuffer b){
ByteOrder holder = b.order();
ByteBuffer ret = b.duplicate();
ret.order(holder);
return ret;
}
這行得通,但是有沒有任何實際方法(不必泛型?)而不必為每種類型(ByteBuffer,FloatBuffer,IntBuffer等)實現此功能?
據編譯器所知,這些不同類上的duplicate
方法之間沒有任何關系。 它們不是由任何超類型(超類或接口)定義的。 因此,它們唯一的共通之處在於它們的方法簽名(名稱和參數),並且唯一的訪問方式是通過反射。 和類似的order
。 這是可能的,但會很混亂,並且會干擾IDE幫助您查看代碼在做什么的能力。 這可能不值得。
此外,還有一個更大的問題:您的方法取決於ByteBuffer#order(ByteOrder)
來設置字節順序; 但是FloatBuffer
和IntBuffer
甚至沒有這種方法。 它們確實具有不帶任何參數並返回其字節順序的order()
,但它們沒有具有字節順序並采用它的order(ByteOrder)
。 (這是因為它們的字節序並不是真正的字節序:如果它們是圍繞字節緩沖區的包裝器,則使用其字節順序;如果它們是圍繞數組的包裝器,則使用系統的字節順序。)
好消息是。 。 。 您不需要為每種類型都實現此方法,因為您不需要。 :-P
您可以結合使用泛型和反射,但這很丑陋:
public static <T extends Buffer> T endianPreservingDuplicate(T b) throws Exception {
Class<?> clazz = b.getClass();
Method getOrder = getMethod(clazz, "order");
ByteOrder orderTemp = (ByteOrder) getOrder.invoke(b);
Method duplicate = getMethod(clazz, "duplicate");
@SuppressWarnings("unchecked") // cast is safe
T copy = (T) duplicate.invoke(b);
Method setOrder = getMethod(clazz, "order", ByteOrder.class);
setOrder.invoke(copy, orderTemp);
return copy;
}
private static Method getMethod(Class<?> clazz, String name, Class<?>...params) throws NoSuchMethodException {
try {
Method method = clazz.getDeclaredMethod(name, params);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
Class<?> superclass = clazz.getSuperclass();
if (!superclass.equals(Buffer.class)) {
return getMethod(superclass, name, params);
} else {
throw new NoSuchMethodException("no " + name + " method");
}
}
}
如果將不帶order()
或duplicate()
的Buffer實現作為b
參數傳遞,則會引發異常。
最好的選擇是為每種緩沖區類型創建單獨的方法。
ruakh的部分功勞,用於審查代碼和建議更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.