Exemplo n.º 1
0
 public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   try {
     Constructor<T> ctor = cls.getDeclaredConstructor();
     if (canFixAccess) {
       checkAndFixAccess(ctor);
     } else {
       // Has to be public...
       if (!Modifier.isPublic(ctor.getModifiers())) {
         throw new IllegalArgumentException(
             "Default constructor for "
                 + cls.getName()
                 + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
       }
     }
     return ctor;
   } catch (NoSuchMethodException e) {;
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e,
         "Failed to find default constructor of class "
             + cls.getName()
             + ", problem: "
             + e.getMessage());
   }
   return null;
 }
Exemplo n.º 2
0
  /**
   * Prints all constructors of a class
   *
   * @param cl a class
   */
  public static void printConstructors(Class cl) {
    Constructor[] constructors = cl.getDeclaredConstructors();

    for (Constructor c : constructors) {
      String name = c.getName();
      System.out.print("   ");
      String modifiers = Modifier.toString(c.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print(name + "(");

      // print parameter types
      Class[] paramTypes = c.getParameterTypes();
      for (int j = 0; j < paramTypes.length; j++) {
        if (j > 0) System.out.print(", ");
        System.out.print(paramTypes[j].getName());
      }
      System.out.println(");");
    }
  }
Exemplo n.º 3
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);
   }
 }