Reputation: 479
private Schema<Message<K, V>> messageSchema = RuntimeSchema.getSchema(Message.class);
As you can see, I'm using a function that requires the class of my Message type. However, I cannot do this as it takes multiple parameters.
Previously, I made an attempt using:
private final Class<K, V> type;
public MessageClass(Class<K, V> type) {
this.type = type;
}
public Class<K, V> getMyType() {
return this.type;
}
However it fell flat on it's face due to Class taking only a single parameter.
Upvotes: 0
Views: 56
Reputation: 20885
When designing APIs that take class definitions, one usually has two choices:
accepting bare classes and don't support parameterized types at all. Users of such libraries will not benefit from the full Java type system, and client code will have unchecked warnings and use raw types
declare Type
parameters and dynamically read type arguments. Users of this kind of libaries will use an idiom known as type token to pass the Type
argument to the library. Demo code
RuntimeSchema.getSchema(new MyTypeToken<Message<String, Integer>>(){{}});
Note that new MyTypeToken<Message<String,Integer>>(){{}}
is an anonymous type that keeps information about type parameters, that otherwise are erased by the compiler and not available at runtime.
Upvotes: 1