Randbedingung
Randbedingung

Reputation: 247

Instance of Generic as method parameter

I am using generics in my class. MyObject must use T as an class, e.g. new MyObject(Long.class). In the method equal I want to ensure that the argument given to the method is an instance of T.

Object<T> is not a valid Java Source, I know. I added it to the code example to show you what I mean, i.e. that value is an instance of T.

But what is the correct way to implement the equal method??

public class MyObject<T extends Class> {

    public boolean equal(Object<T> value) {
        return true;
    }
}

Upvotes: 2

Views: 102

Answers (3)

Amit Deshpande
Amit Deshpande

Reputation: 19185

Assuming that you don't want to override equals. I think you should do below

public class MyObject<T> {

    public boolean isEquals(T obj) {
        return false;
    };
}

There is no need of Class in your case as you are passing Type to MyObject

    MyObject<Long> myObject = new MyObject<Long>();
    myObject.isEquals(Long.valueOf(10);//It will only allow Long
    myObject.isEquals(10);             //Fails for int

References

  1. Generic Types
  2. Lesson: Generics

Upvotes: 0

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

Assuming that you're not out to override Object.equals(Object):

T extends Class makes scant sense because Class is final anyway, so the only thing T could be would be Class<U> for some U, and then you might as well let U be the type parameter. So what you might want it something like:

public class MyClass<T> {
  private Class<T> cl ;
  public MyClass(Class<T> cl) {
    this.cl = cl ;
    ...
  }
  public boolean equal(T value) {
    return true;
  }
}

and you then get to write, say, new MyClass<Long>(Long.class).

But are you sure you need to store the cl parameter at runtime at all? Normally you would leave it out completely, so you just write new MyClass<Long>().

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272257

If you're overriding the equals() method, then you should check the class of the object being used to compare equality with.

  1. The signature will indicate that you can be passed any Object
  2. equality can be defined between different object types (doesn't often happen, but it's valid)

If you're not overriding equals(), I would change your method name to be distinct. Otherwise life is going to be very confusing.

Upvotes: 1

Related Questions