Jin Kwon
Jin Kwon

Reputation: 21978

How to specify a Class of specific generics type?

I know following codes works.

Object get(final String name);

<T> T get(final String name, final Class<T> type) {
    return type.cast(get(name));
}

Is there any way to do this?

get(name, Supplier<ByteBuffer>.class); // compiler doesn't like this.

I currently casting the raw result like this.

(Supplier<ByteBuffer>) get(name);
(Supplier<ByteBuffer>) get(name, Supplier.class);

Upvotes: 0

Views: 29

Answers (1)

syllabus
syllabus

Reputation: 581

if your casts are reliable, you can do this:

@SuppressWarnings("unchecked")
<T> T getWithCast(final String name) {
    return (T) get(name);
}

Upvotes: 1

Related Questions