Isn't there any way to find the class-type of a generic?
if (T instanceof String) {
// do something...
}
The above definitely does not compile.
Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.
void someMethod(Class<T> tClass) {
if(String.class.isAssignableFrom(tClass))
or
void someMethod(Class<T> tClass, T tArg) {
Note: the type might not be the same,
someMethod(Number.class, 1);
T var and how to use it with this method? someMethod(T) won't work... What I don't understand?T var and then I have to check type like this: new Test<T>().something(var)It won't compile because T is not a variable, but a place holder for a class that is defined at runtime. Here's a quick sample:
public class Test<T> {
public void something(T arg) {
if (arg instanceof String) {
System.out.println("Woot!");
}
}
public static void main(String[] args) {
Test<String> t = new Test<String>();
t.something("Hello");
}
}
instanceof to test against a known type, not a generic. What doesn't work is saying if (foo instanceof T) where foo is some variable, because the type that T represents is not known at compile time.if you have subclass
public class SomeClass extends SomeSubclass<String>{}
and
public class SomeSubclass<T> {}
then there is a way to discover type of T by executing code
Type t = getClass().getGenericSuperclass()
if (t instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType)t).getActualTypeArguments()
// in simple cases actualTypeArguments will contain Classes, since Class implements Type
}
if your case are a bit more complex (? extends String)` take a look at org.ormunit.entity.AEntityAccessor#extractClass
Tis a type, not a variable. Only variables can be used on the left-hand side of theinstanceofoperator.