I know there are a lot of questions about similar issues already, but I haven't found one to directly address this one.
Here is the skeleton of the code I'm trying to implement:
class MyObj<T> {
// Internals are unimportant ...
}
private <T> void foo(T arg) {
Class<MyObj<T>> clazz = // What do I write here?
// Here is one thing that works, but is quite ugly:
@SuppressWarnings("unchecked")
clazz = (Class<MyObj<T>>)(new MyObj<T>().getClass())
// ...
// Later, clazz is passed to a constructor of some other class
OtherClass<MyObj<T>> foo = new OtherClass<>(clazz);
}
Question 1: Does anyone have a better suggestion of how to populate clazz
? Ideally, it would avoid calling new
.
Question 2: Given the ugly (but working) code above, are there any situations where it could break? I don't like to @SuppressWarnings
, and worry about problems I might be hiding.