English 中文(简体)
动态类型投放?
原标题:dynamic type casting?

我有一个班子。

A<T> {
    T value;
    public T getValue() { return value; }
    public void setValue(T value) { this.value = value;}
}

并尝试使用非基因方法,如:

A<?>[] as = new A<?>[2]; as[0] = new A<Integer>(); as[1] = new A<String>();
for(A<?> a : as) {
    someobj.put(a.getValue()); // <-- got an error "The method put(String) is not applicable for the arguments (capture#2-of ?)"
}

一些观察家(String s)说(Integer i)等。

怎么能做像动态类型投放和确定错误这样的东西?

最佳回答

如Marko所解释,你通用A的类型已经消失。 但你可以做的是利用思考来援引correct“put”方法。

与此类似:

A<?>[] as = new A<?>[2]; as[0] = new A<Integer>(); as[1] = new A<String>();
for(A<?> a : as) {
    Method m = someobj.getClass().getMethod("put", a.getValue().getClass());
    m.invoke(somobj, a.getValue());
}
问题回答

您在A的即时提供的信息一经您在<代码>A<?>阵列中提供。 汇编者只看到通用课程。

您基本上试图打上<条码>,(Object o),而且确实存在。 你必须服从你希望呼吁的那种论点。 对这种方法的论点,只就其提出的标语而言,没有作出积极的反应。 汇编者必须确切选择哪一种方法——采用(定义)或采用(目标)。 这不能在时间上决定。

理论上,如果你真心想在你的设想中积极派遣,那么你就被迫使用访客模式。 我不建议,这非常麻烦。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签