简体   繁体   English

检查 class 名称不应包含特定文本

[英]Check class name should not contain a Particular text

I have a class the following class University.我有一个 class 下面的 class 大学。

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

I have to write a logic where i need to check each variables in this class and if any variable name like in this case(Canteen Name ,Library Name ) contains a text ' Name ' in it, it should check if it is null or not, other variable it should ignore.我必须编写一个逻辑,我需要检查这个 class 中的每个变量,如果像这种情况下的任何变量名称(食堂名称,图书馆名称)包含一个文本“名称”,它应该检查它是否是 null ,它应该忽略的其他变量。

I thought of doing a null check using the getter property, but is there any dynamic way as the class contain any number of variable like (Canteen Name ).我想过使用 getter 属性进行 null 检查,但是有任何动态方法,因为 class 包含任意数量的变量,例如(食堂名称)。

You can achieve this by using reflection:您可以通过使用反射来实现这一点:

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");
        }   
     }
   }
}

Then in your program:然后在你的程序中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM