我有一个方法看起来像这样。
static <T> void doSomethind(final Class<? super T> type, final T instance) {
}
还有一种方法可以为 T 或 Object 找到合适的超类。
static Class<?> getType(final Object instance) {
// returns a Class which is parent of given instance.
}
我什至不确定这<? super T>
部分是否必要。可以<T>
吗?
static void doSomething(final Object instance) {
final Class<?> type = getType(instance);
// how can I call <T>doSomething(Class<T>, t)?
}
或者
static <T> void doSomething(final T instance) {
final Class<?> type = getType(instance);
// how can I call <T>doSomething(Class<T>, t)?
}
问题是如何调用doSomething(Class, Object)
方法?
更新
我很抱歉。但我什至不知道我在问什么。所以我决定讲一个傻瓜(完整)的故事。
在javax.xml.bind.Marshaller中,有一些方法看起来marshal(Object, XXX)
像
- 元帅(对象,ContentHandler)
- 元帅(对象,文件)
- 等等。
而且我认为我可以像这样使用反射来制作通用实用程序方法。
public static <T> marshal(Marshaller marshaller, Object element,
Class<? super T> targetType, T target)
throws VariousNastyExceptions {
// like a boss, huh?
Marshaller.class.getMethod("marshal", Object.class, targetType)
.invoke(marshaller, element, target);
}
// still not sure about <? super T>
所以任何人都可以像这样调用。
marshal(marshaller, element, OutputStream.class, output);
// say output is an instance of ByteArrayOutputStream
marshal(marshaller, element, Result.class, result);
// say the result is an instance of StreamResult
然后我想要一个没有targetType
.
为此,我首先收集了targetType
.
// InputStream.class, File.class, XMLEventWriter.class, and so on.
static final List<Class<?>> TARGET_TYPES;
static {
final List<Class<?>> targetTypes = new ArrayList<Class<?>>();
for (Method method : Marshaller.class.getMethods()) {
// if method is for marshal(Object, T) // code skipped
targetTypes.add(method.getParameterTypes()[0]);
}
TARGET_TYPES = Collections.unmodifiableList(targetTypes);
}
现在我可以targetType
从给定的Object
.
static Class<?> getTargetType(Object target) {
for (Class<?> targetType : TARGET_TYPES) {
if (targetType.isAssignableFrom(target.getClass())) {
return targetType;
}
}
return null; // don't count this for now
}
我终于尝试了
// do I need a <T> here?
static void marshal(Marshaller marshaller, Object element, Object target) {
final Class<?> targetType = getTargetType(target);
// compiler hates this statement
marshal(marshaller, element, targetType, target);
}
我只想要一个Cipher
用于解密以下消息。
method Marshallers.<T> marshal(Marshaller,Object,Class<? super T>, T) is not applicable
(actual argument Class <CAP#1> cannot be converted to Class<? super Object> by method
invocation conversion)
我想我可以这样做。
static <T> void marshal(Marshaller marshaller, Object element, T target) {
// No ClassCastException guaranteed
@SuppressWarnings("unchecked")
final Class<? super T> targetType =
(Class<? super T>) getTargetType(target);
marshal(marshaller, element, targetType, target);
}
有没有更好的办法?