My method gets Class as a parameter and I have to check that one my variables is of type class.
Volvo v1 = new Volvo();
Class aClass = v1.getClass();
check(aClass);
inside I need to do something like
v2 instanceof aClass ? "True" : "False");
but this doesn;t compile .
You can try also:
Where "aClass" is a superclass of "v2"
As Hovercraft Full Of Eels mentioned, you can generally avoid such explicit method calls by leaning on the compiler to do the checking for you. Some approaches:
You are writing a container of a generically typed thing. Let the type of thing be
T
, then Java allows you to express this as follows:public class MyClass<T> { private T thing; public void setThing(T t) { this.thing = t; } private void check(Class<T> cls) {} // probably not necessary }
Then create instances of
MyClass<T>
as follows:MyClass<Volvo> m = new MyClass<Volvo>();
or since Java 7:MyClass<Volvo> m = new MyClass<>();
You really do need the Class, say because you are working with Enum types and a lot of those methods a parametrized using the relevant Class:
public void check(Class<?extends SuperType> validClsAutomaticallyChecked) {}
You just need an object of a specific supertype to be passed to the method:
public void pass(SuperType thatSimple) {}
You do not need, cannot or will not make your containing class take a type parameter of the thing to be passed, but you still want to leverage generics in your method. This may be useful to allow the compiler to infer that what you are doing inside the method body is safe. For example you may wish to create a collection of things of type
T
based on the type of thing passed as parameter to the method.public <T> void workWith(T genericallyTypedObject) {}
I think you want
aClass.isInstance( v2 )
. The docs say it works the same as theinstanceOf
keyword. I guess they can't useinstanceOf
as a method name because keywords can't be used as method names.Or maybe just use a class literal, if "Volvo" is a constant.