Java Field equals()方法及实例
java.lang.reflect .Field 的 equals() 方法是用来比较两个字段对象。这个方法比较两个字段对象,如果两个对象相等则返回真,否则返回假。两个字段对象被认为是相等的,当且仅当它们由同一个类声明,并且具有相同的名称和类型。这个方法在调试对象属性时非常有帮助,这些属性实际上是Java中类的字段。
语法
public boolean equals(Object obj)
参数: 该方法接受一个参数 obj ,它是要与这个字段对象进行比较的参考对象。
返回值: 如果两个对象相等,该方法返回真,否则返回假。
以下程序说明了equals()方法:
程序1 :
// 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.
程序2 :
// 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://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Field.html#equals(java.lang.Object)