java - How do I check if my object is of type of a

2020-05-30 04:03发布

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 .

标签: java class
4条回答
Juvenile、少年°
2楼-- · 2020-05-30 04:30

You can try also:

aClass.isAssignableFrom(v2.getClass())

Where "aClass" is a superclass of "v2"

查看更多
我想做一个坏孩纸
3楼-- · 2020-05-30 04:36
    Volvo v = new Volvo();
    if (v instanceof Volvo) {
        System.out.println("I'm boxy, but safe.");
    }
查看更多
老娘就宠你
4楼-- · 2020-05-30 04:40

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) {}

查看更多
Summer. ? 凉城
5楼-- · 2020-05-30 04:45

I think you want aClass.isInstance( v2 ). The docs say it works the same as the instanceOf keyword. I guess they can't use instanceOf as a method name because keywords can't be used as method names.

v2 = ???
Volvo v1 = new Volvo();
Class aClass = v1.getClass();
aClass.isInstance( v2 )       // "check(aClass)"

Or maybe just use a class literal, if "Volvo" is a constant.

v2 = ???
Volvo.class.isInstance( v2 );
查看更多
登录 后发表回答