Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Comparing classes?

How can i compare 2 classes?

The following if statement never passes although class is type of MyClass:

public void(Class class) {
   if (class == MyClass.class){

   }
}
like image 771
aryaxt Avatar asked Jun 07 '11 16:06

aryaxt


People also ask

Can you compare classes in Java?

The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)

How do I compare two fields of objects in Java?

reflect. Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type.

How do you compare two POJO objects?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.

How can I compare two Java codes?

The method Files::mismatch, added in Java 12, compares the contents of two files. It returns -1L if the files are identical, and otherwise, it returns the position in bytes of the first mismatch.


1 Answers

To test whether clazz is a (sub) type of MyClass do

MyClass.class.isAssignableFrom(clazz)

From the javadoc for Class.isAssignableFrom

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

So

Object.class.isAssignableFrom(String.class)

is true because each String is also an Object but

String.class.isAssignableFrom(Object.class)

is false because not all Objects are Strings.


The name "isAssignableFrom" comes from the fact that,

Class1 x = (Class2) null;

is only legal when

Class1.class.isAssignableFrom(Class2.class)

I.e., we can assign a field or variable with static type Class1 a value that comes from an expression whose static type is Class2.

like image 81
Mike Samuel Avatar answered Oct 02 '22 14:10

Mike Samuel