Exemplo n.º 1
0
  private void validateClass(Class<?> source, ValidationProblemCollector problems) {
    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
      problems.add("Must be a class, not an interface");
    }

    if (source.getEnclosingClass() != null) {
      if (Modifier.isStatic(modifiers)) {
        if (Modifier.isPrivate(modifiers)) {
          problems.add("Class cannot be private");
        }
      } else {
        problems.add("Enclosed classes must be static and non private");
      }
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterTypes().length > 0) {
        problems.add("Cannot declare a constructor that takes arguments");
        break;
      }
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
      int fieldModifiers = field.getModifiers();
      if (!field.isSynthetic()
          && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
        problems.add(field, "Fields must be static final.");
      }
    }
  }
Exemplo n.º 2
0
 /**
  * Checks if a class fulfills the JavaBeans contract.
  *
  * @param cls the class to check
  */
 public static void checkJavaBean(Class<?> cls) {
   try {
     Constructor<?> constructor = cls.getDeclaredConstructor();
     int classModifiers = cls.getModifiers();
     if (Modifier.isInterface(classModifiers))
       throw new RuntimeException(cls.getName() + " is an interface");
     if (Modifier.isAbstract(classModifiers))
       throw new RuntimeException(
           cls.getName() + " cannot be instantiated - it is an abstract class");
     int modifiers = constructor.getModifiers();
     if (!Modifier.isPublic(modifiers))
       throw new RuntimeException("No public default constructor in " + cls);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("No default constructor in class " + cls);
   } catch (SecurityException e) {
     logger.error(
         "I am not allowed to check the class by using reflection, "
             + "so I just can hope the class is alright and go on: ",
         e);
   }
 }