在我们的项目中,某些数据类(POJO used for API Request & Response)
覆盖了toString()
方法以提供有意义的信息-但是某些数据类没有被覆盖toString()
。
当应用程序打印其中不覆盖logs
的数据类的toString()
时,它们没有打印有意义的信息,它们只是调用对象类toString()
。
因此,我们想识别那些数据类并提供toString()
implementation
。
有什么方法可以识别那些toString()
方法不是implemented
的类。
查找每个数据类并检查toString()
方法是繁琐且耗时的任务。
有没有更好的方法使用Eclipse等工具来做到这一点?
最佳答案
一种方法是使用Reflections Library获取给定包中的所有类,请注意,这不适用于匿名,私有,部分,不可访问,.. etc等类,因此最好的方法是按照@手动进行GhostCat答案
现在,您应该走这条路,这是可以完成的方法,首先通过反射库获取类,该类由@Staale从this answer引用
Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends Object>> allClasses =
reflections.getSubTypesOf(Object.class);
然后遍历这些类,并检查是否在类本身中声明了toString
for(Class clazz : allClasses)
{
if(!clazz.getMethod("toString").getDeclaringClass().getName().equals(clazz.getName()))
System.out.println("toString not overridden in class "+clazz.getName());
}