Oliver Hausler
Oliver Hausler

Reputation: 4987

equals not possible for class?

In Java, I have a function with a signature, where a Type is passed in:

public Object convert(Object object, Type type) {
}

Inside the function, I want to determine if Type is String, but when I do this

String.class.equals(type.getClass())

Android Studio is telling me 'equals()' between objects of inconvertible types 'Class<capture of ? extends Type>' and 'Class<String>'.

What am I doing wrong?

Upvotes: 2

Views: 1159

Answers (4)

iperezmel78
iperezmel78

Reputation: 445

If you want to validate that certain object is a string then you can use a method like this one:

public boolean isStringInstance(Object o) {
    return o instanceof String;
}

So if you run the next code lines:

isStringInstance(new Type());
isStringInstance(new String());

You will get:

false

true

Upvotes: 0

yshavit
yshavit

Reputation: 43391

This is not a javac error — it's something your IDE is providing as a warning (or error, depending on your setting).

That said, in this case the warning is a useful one. You're asking if the class object returned by type.getClass() is equal to the class object represented by the literal String.class. Given that Type is not a superclass of String, I can tell you right now that the answer is false: the Type class is not the same as the String class. Your IDE is trying to tell you the same.

If what you're trying to figure out is whether type instance of type represents the String class, then you don't need the getClass():

String.class.equals(type)

Upvotes: 8

DJClayworth
DJClayworth

Reputation: 26876

type.getClass() does not return the Class represented by type, but the Class of type (which will be the .class of one of the implementations of Type). In other words if "Type" is a Class, then type.getClass() will return the Class object for "Class".

What you need is:

if (type == String.class) {
    ...
}

Upvotes: 2

antoniodvr
antoniodvr

Reputation: 1259

You have to use instanceof on the object rather then the type, replace:

String.class.equals(type.getClass())

by:

if(object instanceof String) {
   // do something
}

The instance of Type in the method signature is not needed for your purpose.

Upvotes: 0

Related Questions