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){
}
}
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)
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.
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.
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.
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 Object
s are String
s.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With