Пример #1
1
 private Object newInstance(Class type) {
   try {
     return type.newInstance();
   } catch (Exception ex) {
     try {
       // Try a private constructor.
       Constructor constructor = type.getDeclaredConstructor();
       constructor.setAccessible(true);
       return constructor.newInstance();
     } catch (SecurityException ignored) {
     } catch (NoSuchMethodException ignored) {
       if (type.isArray())
         throw new SerializationException(
             "Encountered JSON object when expected array of type: " + type.getName(), ex);
       else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
         throw new SerializationException(
             "Class cannot be created (non-static member class): " + type.getName(), ex);
       else
         throw new SerializationException(
             "Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
     } catch (Exception privateConstructorException) {
       ex = privateConstructorException;
     }
     throw new SerializationException(
         "Error constructing instance of class: " + type.getName(), ex);
   }
 }
  /**
   * Uses reflection to fill public fields and optionally Bean properties of the target object from
   * the source Map.
   */
  public static Object fill(Object target, Map<String, Object> source, boolean useProperties)
      throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    if (useProperties) {
      BeanInfo info = Introspector.getBeanInfo(target.getClass());

      PropertyDescriptor[] props = info.getPropertyDescriptors();
      for (int i = 0; i < props.length; ++i) {
        PropertyDescriptor prop = props[i];
        String name = prop.getName();
        Method setter = prop.getWriteMethod();
        if (setter != null && !Modifier.isStatic(setter.getModifiers())) {
          // System.out.println(target + " " + name + " <- " + source.get(name));
          setter.invoke(target, new Object[] {source.get(name)});
        }
      }
    }

    Field[] ff = target.getClass().getDeclaredFields();
    for (int i = 0; i < ff.length; ++i) {
      Field field = ff[i];
      int fieldMod = field.getModifiers();
      if (Modifier.isPublic(fieldMod)
          && !(Modifier.isFinal(fieldMod) || Modifier.isStatic(fieldMod))) {
        // System.out.println(target + " " + field.getName() + " := " +
        // source.get(field.getName()));
        try {
          field.set(target, source.get(field.getName()));
        } catch (IllegalArgumentException iae) {
          // no special error processing required
        }
      }
    }

    return target;
  }
Пример #3
0
 @Test
 public void checkThatOtherMethodsAreNonStatic() throws NoSuchMethodException {
   Method spin = Earth.class.getDeclaredMethod("spin");
   assertFalse("Method spin() should not be static", Modifier.isStatic(spin.getModifiers()));
   Method warmUp = Earth.class.getDeclaredMethod("warmUp");
   assertFalse("Method warmUp() should not be static", Modifier.isStatic(warmUp.getModifiers()));
 }
Пример #4
0
 public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
   if (Modifier.isStatic(method.getModifiers())
       && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
     return invoke(
         method, null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
   } else if (Modifier.isStatic(method.getModifiers())) {
     Object[] args = getActionMethodArgs(method, null);
     args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
     return invoke(method, null, args);
   } else {
     Object instance = null;
     try {
       instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
     } catch (Exception e) {
       Annotation[] annotations = method.getDeclaredAnnotations();
       String annotation = Utils.getSimpleNames(annotations);
       if (!StringUtils.isEmpty(annotation)) {
         throw new UnexpectedException(
             "Method public static void "
                 + method.getName()
                 + "() annotated with "
                 + annotation
                 + " in class "
                 + method.getDeclaringClass().getName()
                 + " is not static.");
       }
       // TODO: Find a better error report
       throw new ActionNotFoundException(Http.Request.current().action, e);
     }
     return invoke(
         method, instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
   }
 }
Пример #5
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.");
      }
    }
  }
Пример #6
0
  public static boolean validClass(Class<?> clazz) {
    try {
      Method serialize = clazz.getDeclaredMethod("serialize");
      if (!serialize.getReturnType().equals(String.class)) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because it does not return a String");
        return false;
      }
      if (!Modifier.isPublic(serialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because the method 'serialize' is not public");
        return false;
      }
      if (!Modifier.isStatic(serialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because the method 'serialize' is static");
        return false;
      }

      Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
      if (!deserialize.getReturnType().equals(clazz)) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' does not return the class '"
                + clazz.getCanonicalName()
                + "'");
        return false;
      }

      if (!Modifier.isStatic(deserialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' is not static");
        return false;
      }
      if (!Modifier.isPublic(deserialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' is not public");
        return false;
      }
    } catch (NoSuchMethodException e) {
      System.out.println(
          "Class '"
              + clazz.getCanonicalName()
              + "' is not deserializable because the method 'deserialize' is does not have either the serialize and/or deserialize method(s)");
      return false;
    }
    return true;
  }
Пример #7
0
  private void analyze(Class<?> cls, boolean topLevel) {
    if (!Modifier.isPublic(cls.getModifiers())) {
      return;
    }

    Lookup lookup = MethodHandles.lookup();

    if (topLevel) {
      this.constructor = new DynamicConstructor(getCoercionMatrix());
      Constructor<?>[] constructors = cls.getConstructors();

      for (int i = 0; i < constructors.length; ++i) {
        try {
          this.constructor.addConstructorHandle(lookup.unreflectConstructor(constructors[i]));
        } catch (IllegalAccessException e) {
        }
      }
    }

    Method[] methods = getTargetClass().getMethods();

    for (int i = 0; i < methods.length; ++i) {
      int modifiers = methods[i].getModifiers();

      if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
        analyzeMethod(methods[i]);
      }
    }

    Field[] fields = getTargetClass().getFields();

    for (int i = 0; i < fields.length; ++i) {
      int modifiers = fields[i].getModifiers();

      if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
        analyzeField(fields[i]);
      }
    }

    if (cls.getSuperclass() != null) {
      analyze(cls.getSuperclass(), false);
    }

    Class<?>[] interfaces = cls.getInterfaces();
    for (int i = 0; i < interfaces.length; ++i) {
      analyze(interfaces[i], false);
    }

    Class<?>[] innerClasses = cls.getDeclaredClasses();

    for (int i = 0; i < innerClasses.length; ++i) {
      int modifiers = innerClasses[i].getModifiers();
      if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
        this.propertyReaders.put(
            innerClasses[i].getSimpleName(), MethodHandles.constant(Class.class, innerClasses[i]));
      }
    }
  }
Пример #8
0
 private Method gatherAnnotations(Class<?> clazz) throws Exception {
   Method factoryMethod = null;
   for (Method m : clazz.getDeclaredMethods()) {
     for (Annotation a : m.getAnnotations()) {
       if (modTypeAnnotations.containsKey(a.annotationType())) {
         Class<?>[] paramTypes = new Class[] {modTypeAnnotations.get(a.annotationType())};
         if (Arrays.equals(m.getParameterTypes(), paramTypes)) {
           m.setAccessible(true);
           eventMethods.put(modTypeAnnotations.get(a.annotationType()), m);
         } else {
           FMLLog.log(
               getModId(),
               Level.SEVERE,
               "The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called",
               getModId(),
               a.annotationType().getSimpleName(),
               Arrays.toString(paramTypes));
         }
       } else if (a.annotationType().equals(Mod.EventHandler.class)) {
         if (m.getParameterTypes().length == 1
             && modAnnotationTypes.containsKey(m.getParameterTypes()[0])) {
           m.setAccessible(true);
           eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
         } else {
           FMLLog.log(
               getModId(),
               Level.SEVERE,
               "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
               getModId(),
               a.annotationType().getSimpleName());
         }
       } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
         if (Modifier.isStatic(m.getModifiers())
             && m.getParameterTypes().length == 0
             && factoryMethod == null) {
           m.setAccessible(true);
           factoryMethod = m;
         } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
           FMLLog.log(
               getModId(),
               Level.SEVERE,
               "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
               m.getName(),
               Arrays.asList(m.getParameterTypes()));
         } else if (factoryMethod != null) {
           FMLLog.log(
               getModId(),
               Level.SEVERE,
               "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
               m.getName(),
               Arrays.asList(m.getParameterTypes()));
         }
       }
     }
   }
   return factoryMethod;
 }
  private void autoInjectGetSet(CtClass ctClass) throws Exception {

    // hibernate 可能需要 setter/getter 方法,好吧 我们为它添加这些方法

    for (CtField ctField : ctClass.getDeclaredFields()) {
      if (isFinal(ctField) || isStatic(ctField) || ctField.hasAnnotation(Validate.class)) continue;
      // Property name
      String propertyName =
          ctField.getName().substring(0, 1).toUpperCase() + ctField.getName().substring(1);
      String getter = "get" + propertyName;
      String setter = "set" + propertyName;

      try {
        CtMethod ctMethod = ctClass.getDeclaredMethod(getter);
        if (ctMethod.getParameterTypes().length > 0 || Modifier.isStatic(ctMethod.getModifiers())) {
          throw new NotFoundException("it's not a getter !");
        }
      } catch (NotFoundException noGetter) {

        String code =
            "public "
                + ctField.getType().getName()
                + " "
                + getter
                + "() { return this."
                + ctField.getName()
                + "; }";
        CtMethod getMethod = CtMethod.make(code, ctClass);
        getMethod.setModifiers(getMethod.getModifiers() | AccessFlag.SYNTHETIC);
        ctClass.addMethod(getMethod);
      }

      try {
        CtMethod ctMethod = ctClass.getDeclaredMethod(setter);
        if (ctMethod.getParameterTypes().length != 1
            || !ctMethod.getParameterTypes()[0].equals(ctField.getType())
            || Modifier.isStatic(ctMethod.getModifiers())) {
          throw new NotFoundException("it's not a setter !");
        }
      } catch (NotFoundException noSetter) {
        CtMethod setMethod =
            CtMethod.make(
                "public void "
                    + setter
                    + "("
                    + ctField.getType().getName()
                    + " value) { this."
                    + ctField.getName()
                    + " = value; }",
                ctClass);
        setMethod.setModifiers(setMethod.getModifiers() | AccessFlag.SYNTHETIC);
        ctClass.addMethod(setMethod);
      }
    }
    ctClass.defrost();
  }
Пример #10
0
  private static String getTypeMetadata(Class<?> clazz) {
    StringBuilder sb = new StringBuilder();

    if (clazz.isInterface()) {
      sb.append("I ");
    } else {
      sb.append("C ");
    }

    if (Modifier.isStatic(clazz.getModifiers())) {
      sb.append("S\n");
    } else {
      sb.append("I\n");
    }

    Class<?> baseClass = clazz.getSuperclass();
    sb.append("B " + ((baseClass != null) ? baseClass.getName() : "").replace('.', '/') + "\n");

    Method[] methods = clazz.getDeclaredMethods();
    Arrays.sort(methods, methodComparator);

    for (Method m : methods) {
      int modifiers = m.getModifiers();
      if (!Modifier.isStatic(modifiers)
          && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) {
        sb.append("M ");
        sb.append(m.getName());
        Class<?>[] params = m.getParameterTypes();
        String sig = MethodResolver.getMethodSignature(m.getReturnType(), params);
        sb.append(" ");
        sb.append(sig);
        int paramCount = params.length;
        sb.append(" ");
        sb.append(paramCount);
        sb.append("\n");
      }
    }

    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
      int modifiers = f.getModifiers();
      if (!Modifier.isStatic(modifiers)
          && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) {
        sb.append("F ");
        sb.append(f.getName());
        sb.append(" ");
        String sig = MethodResolver.getTypeSignature(f.getType());
        sb.append(sig);
        sb.append(" 0\n");
      }
    }

    String ret = sb.toString();

    return ret;
  }
Пример #11
0
  private static void insertGetString(
      ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
    int maxStack = 6;
    MethodVisitor mv =
        cw.visitMethod(
            ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null, null);
    mv.visitCode();
    mv.visitVarInsn(ILOAD, 2);

    if (!fields.isEmpty()) {
      maxStack--;
      Label[] labels = new Label[fields.size()];
      Label labelForInvalidTypes = new Label();
      boolean hasAnyBadTypeLabel = false;
      for (int i = 0, n = labels.length; i < n; i++) {
        if (fields.get(i).getType().equals(String.class)) labels[i] = new Label();
        else {
          labels[i] = labelForInvalidTypes;
          hasAnyBadTypeLabel = true;
        }
      }
      Label defaultLabel = new Label();
      mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

      for (int i = 0, n = labels.length; i < n; i++) {
        if (!labels[i].equals(labelForInvalidTypes)) {
          Field field = fields.get(i);
          mv.visitLabel(labels[i]);
          mv.visitFrame(F_SAME, 0, null, 0, null);
          if (!Modifier.isStatic(field.getModifiers())) {
            mv.visitVarInsn(ALOAD, 1);
            mv.visitTypeInsn(CHECKCAST, classNameInternal);
          }
          mv.visitFieldInsn(
              Modifier.isStatic(field.getModifiers()) ? GETSTATIC : GETFIELD,
              classNameInternal,
              field.getName(),
              "Ljava/lang/String;");
          mv.visitInsn(ARETURN);
        }
      }
      // Rest of fields: different type
      if (hasAnyBadTypeLabel) {
        mv.visitLabel(labelForInvalidTypes);
        mv.visitFrame(F_SAME, 0, null, 0, null);
        insertThrowExceptionForFieldType(mv, "String");
      }
      // Default: field not found
      mv.visitLabel(defaultLabel);
      mv.visitFrame(F_SAME, 0, null, 0, null);
    }
    insertThrowExceptionForFieldNotFound(mv);
    mv.visitMaxs(maxStack, 3);
    mv.visitEnd();
  }
  private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements =
        new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {
      LinkedList<InjectionMetadata.InjectedElement> currElements =
          new LinkedList<InjectionMetadata.InjectedElement>();
      for (Field field : targetClass.getDeclaredFields()) {
        Annotation annotation = findAutowiredAnnotation(field);
        if (annotation != null) {
          if (Modifier.isStatic(field.getModifiers())) {
            if (logger.isWarnEnabled()) {
              logger.warn("Autowired annotation is not supported on static fields: " + field);
            }
            continue;
          }
          boolean required = determineRequiredStatus(annotation);
          currElements.add(new AutowiredFieldElement(field, required));
        }
      }
      for (Method method : targetClass.getDeclaredMethods()) {
        Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
        Annotation annotation =
            BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)
                ? findAutowiredAnnotation(bridgedMethod)
                : findAutowiredAnnotation(method);
        if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
          if (Modifier.isStatic(method.getModifiers())) {
            if (logger.isWarnEnabled()) {
              logger.warn("Autowired annotation is not supported on static methods: " + method);
            }
            continue;
          }
          if (method.getParameterTypes().length == 0) {
            if (logger.isWarnEnabled()) {
              logger.warn(
                  "Autowired annotation should be used on methods with actual parameters: "
                      + method);
            }
          }
          boolean required = determineRequiredStatus(annotation);
          PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
          currElements.add(new AutowiredMethodElement(method, required, pd));
        }
      }
      elements.addAll(0, currElements);
      targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
  }
 private void injectSessionFactory(
     Object test, Iterable<Field> fields, SessionFactory sessionFactory) {
   for (Field field : fields) {
     try {
       if ((test == null && Modifier.isStatic(field.getModifiers()))
           || (test != null && !Modifier.isStatic(field.getModifiers()))) {
         field.set(test, sessionFactory);
       }
     } catch (Exception e) {
       throw new RuntimeException("Can't inject session factory into field " + field);
     }
   }
 }
Пример #14
0
  private Object createChatPacket(String json)
      throws IllegalArgumentException, IllegalAccessException, InstantiationException,
          InvocationTargetException {
    if (nmsChatSerializerGsonInstance == null) {
      // Find the field and its value, completely bypassing obfuscation
      for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) {
        if (Modifier.isFinal(declaredField.getModifiers())
            && Modifier.isStatic(declaredField.getModifiers())
            && declaredField.getType() == com.google.gson.Gson.class) {
          // We've found our field
          declaredField.setAccessible(true);
          nmsChatSerializerGsonInstance = (com.google.gson.Gson) declaredField.get(null);
          break;
        }
      }
    }

    // Since the method is so simple, and all the obfuscated methods have the same name, it's easier
    // to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
    // Of course, the implementation may change, but fuzzy matches might break with signature
    // changes
    Object serializedChatComponent =
        nmsChatSerializerGsonInstance.fromJson(json, Reflection.getNMSClass("IChatBaseComponent"));

    return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
  }
Пример #15
0
 public SysField(java.lang.reflect.Field field) {
   this(
       Modifier.isStatic(field.getModifiers()),
       field.getType().getName(),
       field.getName(),
       SysAnalysis.getVisibility(field.getModifiers()));
 }
 public MethodCollector visitMethod(int access, String name, String desc) {
   // already found the method, skip any processing
   if (collector != null) {
     return null;
   }
   // not the same name
   if (!name.equals(methodName)) {
     return null;
   }
   Type[] argumentTypes = Type.getArgumentTypes(desc);
   int longOrDoubleQuantity = 0;
   for (Type t : argumentTypes) {
     if (t.getClassName().equals("long") || t.getClassName().equals("double")) {
       longOrDoubleQuantity++;
     }
   }
   int paramCount = argumentTypes.length;
   // not the same quantity of parameters
   if (paramCount != this.parameterTypes.length) {
     return null;
   }
   for (int i = 0; i < argumentTypes.length; i++) {
     if (!correctTypeName(argumentTypes, i).equals(this.parameterTypes[i].getName())) {
       return null;
     }
   }
   this.collector =
       new MethodCollector(
           (Modifier.isStatic(access) ? 0 : 1), argumentTypes.length + longOrDoubleQuantity);
   return collector;
 }
Пример #17
0
 private void loadClass() throws SQLException {
   Class<?> javaClass = ClassUtils.loadUserClass(className);
   Method[] methods = javaClass.getMethods();
   ObjectArray<JavaMethod> list = ObjectArray.newInstance();
   for (int i = 0; i < methods.length; i++) {
     Method m = methods[i];
     if (!Modifier.isStatic(m.getModifiers())) {
       continue;
     }
     if (m.getName().equals(methodName) || getMethodSignature(m).equals(methodName)) {
       JavaMethod javaMethod = new JavaMethod(m, i);
       for (JavaMethod old : list) {
         if (old.getParameterCount() == javaMethod.getParameterCount()) {
           throw Message.getSQLException(
               ErrorCode.METHODS_MUST_HAVE_DIFFERENT_PARAMETER_COUNTS_2,
               old.toString(),
               javaMethod.toString());
         }
       }
       list.add(javaMethod);
     }
   }
   if (list.size() == 0) {
     throw Message.getSQLException(
         ErrorCode.PUBLIC_STATIC_JAVA_METHOD_NOT_FOUND_1, methodName + " (" + className + ")");
   }
   javaMethods = new JavaMethod[list.size()];
   list.toArray(javaMethods);
   // Sort elements. Methods with a variable number of arguments must be at
   // the end. Reason: there could be one method without parameters and one
   // with a variable number. The one without parameters needs to be used
   // if no parameters are given.
   Arrays.sort(javaMethods);
 }
Пример #18
0
  /**
   * Invokes a static "main(argv[]) method on class "className". Converts various failing exceptions
   * into RuntimeExceptions, with the assumption that they will then cause the VM instance to exit.
   *
   * @param loader class loader to use
   * @param className Fully-qualified class name
   * @param argv Argument vector for main()
   */
  static void invokeStaticMain(ClassLoader loader, String className, String[] argv)
      throws ZygoteInit.MethodAndArgsCaller {
    Class<?> cl;

    try {
      cl = loader.loadClass(className);
    } catch (ClassNotFoundException ex) {
      throw new RuntimeException("Missing class when invoking static main " + className, ex);
    }

    Method m;
    try {
      m = cl.getMethod("main", new Class[] {String[].class});
    } catch (NoSuchMethodException ex) {
      throw new RuntimeException("Missing static main on " + className, ex);
    } catch (SecurityException ex) {
      throw new RuntimeException("Problem getting static main on " + className, ex);
    }

    int modifiers = m.getModifiers();
    if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
      throw new RuntimeException("Main method is not public and static on " + className);
    }

    /*
     * This throw gets caught in ZygoteInit.main(), which responds
     * by invoking the exception's run() method. This arrangement
     * clears up all the stack frames that were required in setting
     * up the process.
     */
    throw new ZygoteInit.MethodAndArgsCaller(m, argv);
  }
Пример #19
0
 private void addFields(Class<?> clazz) {
   Field[] fields = clazz.getDeclaredFields();
   for (Field field : fields) {
     if (canAccessPrivateMethods()) {
       try {
         field.setAccessible(true);
       } catch (Exception e) {
         // Ignored. This is only a final precaution, nothing we can do.
       }
     }
     if (field.isAccessible()) {
       if (!setMethods.containsKey(field.getName())) {
         // issue #379 - removed the check for final because JDK 1.5 allows
         // modification of final fields through reflection (JSR-133). (JGB)
         // pr #16 - final static can only be set by the classloader
         int modifiers = field.getModifiers();
         if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
           addSetField(field);
         }
       }
       if (!getMethods.containsKey(field.getName())) {
         addGetField(field);
       }
     }
   }
   if (clazz.getSuperclass() != null) {
     addFields(clazz.getSuperclass());
   }
 }
  public void testOverrideMethods() throws Exception {
    HashSet<String> methodsThatShouldNotBeOverridden = new HashSet<String>();
    methodsThatShouldNotBeOverridden.add("reopen");
    methodsThatShouldNotBeOverridden.add("doOpenIfChanged");
    methodsThatShouldNotBeOverridden.add("clone");
    boolean fail = false;
    for (Method m : FilterIndexReader.class.getMethods()) {
      int mods = m.getModifiers();
      if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || m.isSynthetic()) {
        continue;
      }
      Class<?> declaringClass = m.getDeclaringClass();
      String name = m.getName();
      if (declaringClass != FilterIndexReader.class
          && declaringClass != Object.class
          && !methodsThatShouldNotBeOverridden.contains(name)) {
        System.err.println("method is not overridden by FilterIndexReader: " + name);
        fail = true;
      } else if (declaringClass == FilterIndexReader.class
          && methodsThatShouldNotBeOverridden.contains(name)) {
        System.err.println("method should not be overridden by FilterIndexReader: " + name);
        fail = true;
      }
    }
    assertFalse(
        "FilterIndexReader overrides (or not) some problematic methods; see log above", fail);

    // some more inner classes:
    checkOverrideMethods(FilterIndexReader.FilterTermEnum.class);
    checkOverrideMethods(FilterIndexReader.FilterTermDocs.class);
    // TODO: FilterTermPositions should extend correctly, this is borken,
    // but for backwards compatibility we let it be:
    // checkOverrideMethods(FilterIndexReader.FilterTermPositions.class);
  }
Пример #21
0
  /**
   * Invokes main() method on class with provided parameters.
   *
   * @param sClass class name in form "MyClass" for default package or "com.abc.MyClass" for class
   *     in some package
   * @param args arguments for the main() method or null.
   * @throws Throwable wrapper for many exceptions thrown while
   *     <p>(1) main() method lookup: ClassNotFoundException, SecurityException,
   *     NoSuchMethodException
   *     <p>(2) main() method launch: IllegalArgumentException, IllegalAccessException (disabled)
   *     <p>(3) Actual cause of InvocationTargetException
   *     <p>See {@link
   *     http://java.sun.com/developer/Books/javaprogramming/JAR/api/jarclassloader.html} and {@link
   *     http://java.sun.com/developer/Books/javaprogramming/JAR/api/example-1dot2/JarClassLoader.java}
   */
  public void invokeMain(String sClass, String[] args) throws Throwable {
    Class<?> clazz = loadClass(sClass);
    logInfo(LogArea.CONFIG, "Launch: %s.main(); Loader: %s", sClass, clazz.getClassLoader());
    Method method = clazz.getMethod("main", new Class<?>[] {String[].class});

    boolean bValidModifiers = false;
    boolean bValidVoid = false;

    if (method != null) {
      method.setAccessible(true); // Disable IllegalAccessException
      int nModifiers = method.getModifiers(); // main() must be "public static"
      bValidModifiers = Modifier.isPublic(nModifiers) && Modifier.isStatic(nModifiers);
      Class<?> clazzRet = method.getReturnType(); // main() must be "void"
      bValidVoid = (clazzRet == void.class);
    }
    if (method == null || !bValidModifiers || !bValidVoid) {
      throw new NoSuchMethodException("The main() method in class \"" + sClass + "\" not found.");
    }

    // Invoke method.
    // Crazy cast "(Object)args" because param is: "Object... args"
    try {
      method.invoke(null, (Object) args);
    } catch (InvocationTargetException e) {
      throw e.getTargetException();
    }
  } // invokeMain()
Пример #22
0
 @SuppressWarnings("unchecked")
 protected static <T extends Bits<T>> T[] _values(Class<T> cls) {
   if (!Bits.class.isAssignableFrom(cls)) {
     throw new IllegalArgumentException(cls.getName() + " is not a subclass of " + Bits.class);
   }
   try {
     Set<T> values = new TreeSet<T>();
     for (Field field : cls.getDeclaredFields()) {
       int mod = field.getModifiers();
       if (Modifier.isPublic(mod)
           && Modifier.isStatic(mod)
           && Modifier.isFinal(mod)
           && field.getType() == cls) {
         T bits = (T) field.get(null);
         Bits<?> bits_ =
             bits; // Avoids "... has private access in Bits" error with javac from OpenJDK 1.7
         bits_.name = field.getName();
         if (bits_.mask != 0) {
           values.add(bits);
         }
       }
     }
     return (T[]) values.toArray((T[]) Array.newInstance(cls, values.size()));
   } catch (IllegalAccessException e) {
     throw new Error(e);
   }
 }
Пример #23
0
 public FieldDefinition(Field field) {
   this.name = field.getName();
   this.type = field.getType().getName();
   this.isStatic = Modifier.isStatic(field.getModifiers());
   this.isPublic =
       !Modifier.isPrivate(field.getModifiers()) && !Modifier.isProtected(field.getModifiers());
 }
Пример #24
0
  private ObjectMap<String, FieldMetadata> cacheFields(Class type) {
    ArrayList<Field> allFields = new ArrayList();
    Class nextClass = type;
    while (nextClass != Object.class) {
      Collections.addAll(allFields, nextClass.getDeclaredFields());
      nextClass = nextClass.getSuperclass();
    }

    ObjectMap<String, FieldMetadata> nameToField = new ObjectMap();
    for (int i = 0, n = allFields.size(); i < n; i++) {
      Field field = allFields.get(i);

      int modifiers = field.getModifiers();
      if (Modifier.isTransient(modifiers)) continue;
      if (Modifier.isStatic(modifiers)) continue;
      if (field.isSynthetic()) continue;

      if (!field.isAccessible()) {
        try {
          field.setAccessible(true);
        } catch (AccessControlException ex) {
          continue;
        }
      }

      nameToField.put(field.getName(), new FieldMetadata(field));
    }
    typeToFields.put(type, nameToField);
    return nameToField;
  }
  /**
   * Resolve the factory method in the specified bean definition, if possible. {@link
   * RootBeanDefinition#getResolvedFactoryMethod()} can be checked for the result.
   *
   * @param mbd the bean definition to check
   */
  public void resolveFactoryMethodIfPossible(RootBeanDefinition mbd) {
    Class<?> factoryClass;
    boolean isStatic;
    if (mbd.getFactoryBeanName() != null) {
      factoryClass = this.beanFactory.getType(mbd.getFactoryBeanName());
      isStatic = false;
    } else {
      factoryClass = mbd.getBeanClass();
      isStatic = true;
    }
    factoryClass = ClassUtils.getUserClass(factoryClass);

    Method[] candidates = getCandidateMethods(factoryClass, mbd);
    Method uniqueCandidate = null;
    for (Method candidate : candidates) {
      if (Modifier.isStatic(candidate.getModifiers()) == isStatic
          && mbd.isFactoryMethod(candidate)) {
        if (uniqueCandidate == null) {
          uniqueCandidate = candidate;
        } else if (!Arrays.equals(
            uniqueCandidate.getParameterTypes(), candidate.getParameterTypes())) {
          uniqueCandidate = null;
          break;
        }
      }
    }
    synchronized (mbd.constructorArgumentLock) {
      mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
    }
  }
  /**
   * Registers the metadata from an element subclass using its "registerMetadata" method through
   * reflection.
   */
  public synchronized MetadataRegistry registerClass(Class<? extends Element> clazz) {

    // Element itself does not require registration, so skip it.
    if (Element.class == clazz) {
      return this;
    }
    try {
      Method registerMethod = clazz.getDeclaredMethod("registerMetadata", MetadataRegistry.class);

      if (!Modifier.isStatic(registerMethod.getModifiers())) {
        throw new IllegalArgumentException(
            "Class " + clazz + " had a non-static registerMetadata(MetadataRegistry) method.");
      }
      registerMethod.invoke(null, this);
      return this;
    } catch (SecurityException e) {
      // Something fishy is going on, rethrow a runtime exception.
      throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
      // No "registerMetadata" method found, throw an exception.
      throw new IllegalArgumentException(
          "Class " + clazz + " doesn't support metadata registration.", e);
    } catch (IllegalAccessException e) {
      // Method wasn't public, throw an illegal argument exception.
      throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
      // Our registration method threw an exception!  Rethrown the nested
      // exception in an illegal argument exception.
      throw new IllegalArgumentException(e.getCause());
    }
  }
Пример #27
0
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new LinkedHashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     int mod = f.getModifiers();
     if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class)) {
       continue;
     }
     if (f.isAnnotationPresent(NoBinding.class)) {
       NoBinding a = f.getAnnotation(NoBinding.class);
       List<String> values = Arrays.asList(a.value());
       if (values.contains("*")) {
         continue;
       }
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
Пример #28
0
 private static java.util.List printFields(
     StringBuffer out,
     Object o,
     java.lang.reflect.Field[] fields,
     java.util.List fieldNames,
     Conf conf) {
   for (int i = 0; i < fields.length; i++) {
     if (java.lang.reflect.Modifier.isPublic(fields[i].getModifiers())
         && !java.lang.reflect.Modifier.isStatic(fields[i].getModifiers())) {
       String key = fields[i].getName();
       if (fieldNames.contains(key)) continue;
       Object value;
       try {
         value = fields[i].get(o);
       } catch (IllegalArgumentException e) {
         throw new RuntimeException();
       } catch (IllegalAccessException e) {
         throw new RuntimeException();
       }
       fieldNames.add(key);
       printKeyValue(out, key, value, conf);
     }
   }
   return fieldNames;
 }
Пример #29
0
  @Test
  public void testInheritedMethodsImplemented() throws Exception {
    int errors = 0;
    for (Method m : FileSystem.class.getDeclaredMethods()) {
      if (Modifier.isStatic(m.getModifiers())
          || Modifier.isPrivate(m.getModifiers())
          || Modifier.isFinal(m.getModifiers())) {
        continue;
      }

      try {
        MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes());
        try {
          HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
          LOG.error("HarFileSystem MUST not implement " + m);
          errors++;
        } catch (NoSuchMethodException ex) {
          // Expected
        }
      } catch (NoSuchMethodException exc) {
        try {
          HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
        } catch (NoSuchMethodException exc2) {
          LOG.error("HarFileSystem MUST implement " + m);
          errors++;
        }
      }
    }
    assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0);
  }
Пример #30
0
 private static void reflectionAppend(
     Object obj,
     Object obj1,
     Class class1,
     CompareToBuilder comparetobuilder,
     boolean flag,
     String as[]) {
   Field afield[] = class1.getDeclaredFields();
   AccessibleObject.setAccessible(afield, true);
   int i = 0;
   do {
     if (i >= afield.length || comparetobuilder.comparison != 0) {
       return;
     }
     Field field = afield[i];
     if (!ArrayUtils.contains(as, field.getName())
         && field.getName().indexOf('$') == -1
         && (flag || !Modifier.isTransient(field.getModifiers()))
         && !Modifier.isStatic(field.getModifiers())) {
       try {
         comparetobuilder.append(field.get(obj), field.get(obj1));
       } catch (IllegalAccessException illegalaccessexception) {
         throw new InternalError("Unexpected IllegalAccessException");
       }
     }
     i++;
   } while (true);
 }