java实现使用注解配置字段,完成从大到小的方式进行遍历,拿到为空的字段 请代码实例
时间: 2024-04-30 18:23:27 浏览: 20
以下是一个示例代码,演示了如何使用注解配置字段,从大到小遍历对象的字段,并找到为空的字段:
```
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Nullable {
}
class ExampleObject {
@Nullable
private Integer field1 = null;
private String field2 = "test";
@Nullable
private Double field3 = null;
}
public class Main {
public static void main(String[] args) {
ExampleObject obj = new ExampleObject();
obj.field1 = 1;
obj.field3 = 2.0;
Field[] fields = ExampleObject.class.getDeclaredFields();
Arrays.sort(fields, (a, b) -> {
Nullable n1 = a.getAnnotation(Nullable.class);
Nullable n2 = b.getAnnotation(Nullable.class);
if (n1 == null && n2 == null)
return 0;
if (n1 == null)
return 1;
if (n2 == null)
return -1;
return 0;
});
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(obj);
if (value == null) {
System.out.println(field.getName() + " is null");
} else {
System.out.println(field.getName() + " = " + value.toString());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们定义了一个`Nullable`注解,用于标记可为空的字段。然后我们创建了一个`ExampleObject`类,其中包含了三个字段,其中`field1`和`field3`被标记为可为空。
在`Main`类中,我们获取了`ExampleObject`类中的所有字段,并使用`Arrays.sort()`方法将它们按照是否可为空的顺序排序。然后我们遍历每个字段,并通过`field.get(obj)`方法获取字段的值。如果值为空,则打印出该字段的名称。否则,打印出该字段的名称和值。
当我们运行这个程序时,它会输出以下内容:
```
field3 is null
field2 = test
field1 = 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)