Java中的字段 equals() 方法及示例
Java.lang.reflect.Field的equals()方法用于比较两个字段对象。此方法比较两个字段对象,如果两个对象相等则返回 true,否则返回 false。当且仅当它们由同一个类声明并且具有相同的名称和类型时,这两个 Field 对象才被认为是相等的。这种方法在调试对象属性时非常有用,这些属性实际上是Java中类的字段。
句法:
public boolean equals(Object obj)
参数:此方法接受一个参数obj ,它是要与此 Field 对象进行比较的参考对象。
返回值:如果两个对象相等,则此方法返回 true,否则返回 false。
下面的程序说明了 equals() 方法:
方案一:
// Java program to demonstrate the above method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException
{
// get the array of Field objects
Field[] fields
= User.class.getDeclaredFields();
Field fieldObj
= User.class.getField("name");
// print element of field array
// and compare it with fieldObj
for (int i = 0; i < fields.length; i++) {
// compare the fields with each other
boolean isEquals
= fields[i].equals(fieldObj);
if (isEquals) {
System.out.println(
"Field -> ["
+ fields[i] + "] and"
+ " FieldObj -> ["
+ fieldObj
+ "] are equal.");
}
else {
System.out.println(
"Field -> ["
+ fields[i] + "] and"
+ " FieldObj -> ["
+ fieldObj
+ "] are not equal.");
}
}
}
}
// User class
class User {
public String name;
public int age;
}
Field -> [public java.lang.String User.name]
and
FieldObj -> [public java.lang.String User.name]
are equal.
Field -> [public int User.age]
and
FieldObj -> [public java.lang.String User.name]
are not equal.
方案二:
// Java program to demonstrate the above method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException
{
// get the array of Field objects
Field[] fields1
= Class.class.getDeclaredFields();
Field[] fields2
= Class.class.getDeclaredFields();
// print element of field array 1 and compare
// it with fields array 2
for (int i = 0; i < fields1.length; i++) {
for (int j = 0; j < fields2.length; j++) {
// compare the fields with each other
boolean isEquals
= fields1[i].equals(fields2[j]);
if (isEquals) {
System.out.println(
"Field -> ["
+ fields1[i] + "] and"
+ " FieldObj -> ["
+ fields2[j]
+ "] are equal.");
}
else {
System.out.println(
"Field -> ["
+ fields1[i] + "] and"
+ " FieldObj -> ["
+ fields2[j]
+ "] are not equal.");
}
}
}
}
}
// Object of Class which contains
// noOfStudents and studentNames
class Class {
public int noOfStudents;
public String[] studentNames;
}
Field -> [public int Class.noOfStudents]
and
FieldObj -> [public int Class.noOfStudents]
are equal.
Field -> [public int Class.noOfStudents]
and
FieldObj -> [public java.lang.String[] Class.studentNames]
are not equal.
Field -> [public java.lang.String[] Class.studentNames]
and
FieldObj -> [public int Class.noOfStudents]
are not equal.
Field -> [public java.lang.String[] Class.studentNames]
and
FieldObj -> [public java.lang.String[] Class.studentNames]
are equal.
参考资料: https: Java Java.lang.Object)