java - 检查类名不应包含特定文本

标签 java class object variables

我在大学下面的类(class)有一个类(class)。

public class University {
private List<Student> Students = null;
private List<Departments> department;
private CanteenName canteenName;
private LibraryName libraryName;
}

我必须编写一个逻辑,我需要检查此类中的每个变量,以及是否有像本例中那样的变量名称(CanteenName ,LibraryName)包含其中的文本“Name”,它应该检查它是否为空,它应该忽略其他变量。

我想过使用 getter 属性进行 null 检查,但是有没有任何动态方法,因为该类包含任意数量的变量,如 (CanteenName)。

最佳答案

您可以通过使用反射来实现这一点:

public static void checkObjectFieldForNull(Object obj, String... fieldNames) throws Exception {
   if (obj == null) return;
   //get all the fields in the object
   for (Field f : obj.getClass().getDeclaredFields()) {
     f.setAccessible(true); //set the fields to be accessible
     for (String str : fieldNames) {
        //loop through the fieldNames and see if they are null
        if (f.getName().toLowerCase().contains(str.toLowerCase())) {
          Obj val = f.get(obj);
          //throw an exception if any of the required fields are null
          if (val == null) throw new Exception(f.getName() + " cannot be null");
        }   
     }
   }
}

然后在你的程序中:

public static void main(String[] args) {
   University u = new University();
   checkObjectFieldForNull(u, "name");
}

关于java - 检查类名不应包含特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58628055/

相关文章:

java - JASYPT 与 Spring Boot 问题加密强密码并在应用程序中使用它

java - 在 Activity 中心添加进度对话框

c++ - 让类存储未知数据

validation - 有没有办法合并 Joi 模式?

python - 如何获取未初始化实例的属性?

ruby - 这段 Ruby 代码的作用是什么? : def self. 元类;类<< self ;自己;结尾;结尾

java - 在 ArrayBlockingQueue 中,为什么要将 final 成员字段复制到本地 final 变量中?

java - 使用类名从 Java Vector 检索对象

c++ - 如何正确制作带有 templetad 数组的类对象?

c# - 在 C# 中使用抽象类