コード例 #1
1
ファイル: CCommon.java プロジェクト: LightJason/AgentSpeak
  /**
   * reads all methods by the action-annotations for building agent-actions
   *
   * @param p_class class
   * @param p_root root class
   * @return stream of all methods with inheritance
   */
  private static Stream<Method> methods(final Class<?> p_class, final Class<?> p_root) {
    final Pair<Boolean, IAgentAction.EAccess> l_classannotation = CCommon.isActionClass(p_class);
    if (!l_classannotation.getLeft())
      return p_class.getSuperclass() == null
          ? Stream.of()
          : methods(p_class.getSuperclass(), p_root);

    final Predicate<Method> l_filter =
        IAgentAction.EAccess.WHITELIST.equals(l_classannotation.getRight())
            ? i -> !CCommon.isActionFiltered(i, p_root)
            : i -> CCommon.isActionFiltered(i, p_root);

    return Stream.concat(
        Arrays.stream(p_class.getDeclaredMethods())
            .parallel()
            .map(
                i -> {
                  i.setAccessible(true);
                  return i;
                })
            .filter(i -> !Modifier.isAbstract(i.getModifiers()))
            .filter(i -> !Modifier.isInterface(i.getModifiers()))
            .filter(i -> !Modifier.isNative(i.getModifiers()))
            .filter(i -> !Modifier.isStatic(i.getModifiers()))
            .filter(l_filter),
        methods(p_class.getSuperclass(), p_root));
  }
コード例 #2
1
 @SuppressWarnings("rawtypes")
 private <O extends Operator> O newInstance(Class<O> c) {
   if (c.isInterface()) {
     return null;
   }
   if (Modifier.isAbstract(c.getModifiers())) {
     return null;
   }
   final Class<?>[] paramTypes;
   final Object[] args;
   if (Modifier.isStatic(c.getModifiers())) {
     paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
     args = ArrayUtils.EMPTY_OBJECT_ARRAY;
   } else {
     paramTypes = new Class[] {getClass()};
     args = new Object[] {this};
   }
   final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes);
   if (cs == null) {
     return null;
   }
   try {
     return cs.newInstance(args);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
コード例 #3
0
 /**
  * EJB 3.1 spec mandates that the view should allow invocation on only public, non-final,
  * non-static methods. This method returns true if the passed {@link Method method} is public,
  * non-static and non-final. Else returns false.
  */
 protected boolean isInvocationAllowed(Method method) {
   int m = method.getModifiers();
   // We handle only public, non-static, non-final methods
   if (!Modifier.isPublic(m)) {
     if (logger.isTraceEnabled()) {
       logger.trace("Method " + method + " is *not* public");
     }
     // it's not a public method
     return false;
   }
   if (Modifier.isFinal(m)) {
     if (logger.isTraceEnabled()) {
       logger.trace("Method " + method + " is final");
     }
     // it's a final method
     return false;
   }
   if (Modifier.isStatic(m)) {
     if (logger.isTraceEnabled()) {
       logger.trace("Method " + method + " is static");
     }
     // it's a static method
     return false;
   }
   if (Modifier.isNative(m)) {
     if (logger.isTraceEnabled()) {
       logger.trace("Method " + method + " is native");
     }
     // it's a native method
     return false;
   }
   // we handle rest of the methods
   return true;
 }
コード例 #4
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());
 }
コード例 #5
0
ファイル: JPAPlugin.java プロジェクト: visan/play1
 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;
 }
コード例 #6
0
ファイル: ClassUtils.java プロジェクト: PAMSE/APGBench
  /**
   * Returns the desired Method much like <code>Class.getMethod</code>, however it ensures that the
   * returned Method is from a public class or interface and not from an anonymous inner class. This
   * means that the Method is invokable and doesn't fall foul of Java bug <a
   * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>). <code>
   * <pre>Set set = Collections.unmodifiableSet(...);
   *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
   *  Object result = method.invoke(set, new Object[]);</pre></code>
   *
   * @param cls the class to check, not null
   * @param methodName the name of the method
   * @param parameterTypes the list of parameters
   * @return the method
   * @throws NullPointerException if the class is null
   * @throws SecurityException if a a security violation occured
   * @throws NoSuchMethodException if the method is not found in the given class or if the metothod
   *     doen't conform with the requirements
   */
  public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[])
      throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
      return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
    candidateClasses.addAll(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
      if (!Modifier.isPublic(candidateClass.getModifiers())) {
        continue;
      }
      Method candidateMethod;
      try {
        candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
      } catch (NoSuchMethodException ex) {
        continue;
      }
      if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
        return candidateMethod;
      }
    }

    throw new NoSuchMethodException(
        "Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes));
  }
コード例 #7
0
ファイル: Reflector.java プロジェクト: huangfan575/mybatis-3
 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());
   }
 }
コード例 #8
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()
コード例 #9
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);
 }
コード例 #10
0
ファイル: LE.java プロジェクト: allanfish/yufei-facetime
 /**
  * 是否规定的忽略字段
  *
  * @param f
  * @return
  */
 public static boolean isIgnoredField(Field f) {
   int mods = f.getModifiers();
   return Modifier.isStatic(mods)
       || Modifier.isFinal(mods)
       || Modifier.isTransient(mods)
       || f.getName().startsWith("this$");
 }
コード例 #11
0
ファイル: Reflections.java プロジェクト: liyq1406/melonePos
 /** 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */
 public static void makeAccessible(Method method) {
   if ((!Modifier.isPublic(method.getModifiers())
           || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
       && !method.isAccessible()) {
     method.setAccessible(true);
   }
 }
コード例 #12
0
 /**
  * @param clazz
  * @param constantName
  * @param declared
  * @return
  */
 public static String getStringConstant(Class<?> clazz, String constantName, boolean declared) {
   Field compType = null;
   try {
     // check if there's a
     // public static final String COMPONENT_TYPE = "...";
     compType = declared ? clazz.getDeclaredField(constantName) : clazz.getField(constantName);
   } catch (SecurityException e) {
     // if no such field, fall through
   } catch (NoSuchFieldException e) {
     // if no such field, fall through
   }
   if (null == compType) return null;
   int modifiers = compType.getModifiers();
   if (!Modifier.isStatic(modifiers)
       || !Modifier.isPublic(modifiers)
       || !Modifier.isFinal(modifiers)
       || String.class != compType.getType()) {
     return null;
   }
   try {
     return (String) compType.get(null);
   } catch (IllegalArgumentException e1) {
     // shouldn't happen - the arg is of the correct type
     e1.printStackTrace();
   } catch (IllegalAccessException e1) {
     // shouldn't happen - the method is public
     e1.printStackTrace();
   } catch (NullPointerException e1) {
     // shouldn't happen - allowed a null arg when
     // the field is static
     e1.printStackTrace();
   }
   return null;
 }
コード例 #13
0
  private void writeToFile(final Object object, final int depth, final Class clazz)
      throws IllegalAccessException {
    for (Field field : clazz.getDeclaredFields()) {
      final int modifier = field.getModifiers();
      if (Modifier.isPrivate(modifier)
          && !Modifier.isTransient(modifier)
          && !Modifier.isStatic(modifier)) {
        field.setAccessible(true);

        final Object data = field.get(object);
        if (writeKey(field, depth, data)) {
          continue;
        }
        if (data instanceof StorageObject) {
          writer.println();
          writeToFile(data, depth + 1, data.getClass());
        } else if (data instanceof Map) {
          writeMap((Map<Object, Object>) data, depth + 1);
        } else if (data instanceof Collection) {
          writeCollection((Collection<Object>) data, depth + 1);
        } else if (data instanceof Location) {
          writeLocation((Location) data, depth + 1);
        } else {
          writeScalar(data);
          writer.println();
        }
      }
    }
  }
コード例 #14
0
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new HashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     if (Modifier.isTransient(f.getModifiers())) {
       continue;
     }
     if (Modifier.isStatic(f.getModifiers())) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class) && !f.getType().equals(Blob.class)) {
       continue;
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
コード例 #15
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;
  }
コード例 #16
0
ファイル: SynchronizedTest.java プロジェクト: Fiurgeist/orbit
  @Test
  public void synchronizedMethod() {
    class SynchronizedMethodExperiment {
      int x;

      synchronized Task doIt(int a) {
        x = 1;
        this.notify();
        await(getBlockedTask());
        this.notify();
        return fromValue(x);
      }
    }
    final Task res = new SynchronizedMethodExperiment().doIt(0);
    Method asyncMethod =
        Stream.of(SynchronizedMethodExperiment.class.getDeclaredMethods())
            .filter(m -> m.getName().startsWith("async$"))
            .findFirst()
            .orElse(null);
    completeFutures();
    assertEquals(1, res.join());

    // it must be false since the async method is static
    assertFalse(Modifier.isSynchronized(asyncMethod.getModifiers()));
    assertTrue(Modifier.isStatic(asyncMethod.getModifiers()));
  }
コード例 #17
0
 @Override
 public boolean canAccessMethod(Method method) {
   Objects.requireNonNull(method, "Null method");
   return Modifier.isPublic(method.getModifiers())
       && Modifier.isPublic(method.getDeclaringClass().getModifiers())
       && Modifier.isPublic(method.getParameterTypes()[0].getModifiers());
 }
コード例 #18
0
ファイル: Mirror.java プロジェクト: jekey/nutz
 /** @return 所有静态方法 */
 public Method[] getStaticMethods() {
   List<Method> list = new LinkedList<Method>();
   for (Method m : klass.getMethods()) {
     if (Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) list.add(m);
   }
   return list.toArray(new Method[list.size()]);
 }
コード例 #19
0
ファイル: Bits.java プロジェクト: zhongfuqiang/robovm
 @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);
   }
 }
コード例 #20
0
  /**
   * @return a reference to the public static serializableInstance() method of clazz, if there is
   *     one; otherwise, returns null.
   */
  private Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
      if ("serializableInstance".equals(method.getName())) {
        Class[] parameterTypes = method.getParameterTypes();

        if (!(parameterTypes.length == 0)) {
          continue;
        }

        if (!(Modifier.isStatic(method.getModifiers()))) {
          continue;
        }

        if (Modifier.isAbstract(method.getModifiers())) {
          continue;
        }

        return method;
      }
    }

    return null;
  }
コード例 #21
0
ファイル: PrettyPrinter.java プロジェクト: dexgeh/JavaHelpers
 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;
 }
コード例 #22
0
 private Bytecode createAbstractMethodCode(ClassFile file, MethodInformation method)
     throws NotFoundException {
   if ((delegateField != null) && (!Modifier.isPrivate(delegateField.getModifiers()))) {
     // Call the corresponding method directly on the delegate
     Bytecode b = new Bytecode(file.getConstPool());
     int localVariables = MethodUtils.calculateMaxLocals(method.getMethod());
     b.setMaxLocals(localVariables);
     // load the delegate field
     b.addAload(0);
     b.addGetfield(
         file.getName(),
         delegateField.getName(),
         DescriptorUtils.classToStringRepresentation(delegateField.getType()));
     // load the parameters
     BytecodeUtils.loadParameters(b, method.getDescriptor());
     // invoke the delegate method
     b.addInvokeinterface(
         delegateField.getType().getName(),
         method.getName(),
         method.getDescriptor(),
         localVariables);
     // return the value if applicable
     BytecodeUtils.addReturnInstruction(b, method.getReturnType());
     return b;
   } else {
     if (!Modifier.isPrivate(method.getMethod().getModifiers())) {
       // if it is a parameter injection point we need to initalize the
       // injection point then handle the method with the method handler
       return createAbstractMethodHandler(file, method);
     } else {
       // if the delegate is private we need to use the method handler
       return createInterceptorBody(file, method);
     }
   }
 }
コード例 #23
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);
  }
コード例 #24
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()));
 }
コード例 #25
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);
  }
コード例 #26
0
  /** {@inheritDoc} */
  @Override
  public String createFullLevelDefinition(Class objectClass) {
    Map<String, String> map = getLevelMapForClass(objectClass);
    if (map == null) {
      map = new HashMap<String, String>();
      getLevelMap().put(objectClass, map);
    }

    String levelDefinition = "";
    while (objectClass != null && objectClass != Object.class) {
      final Field[] fieldList = objectClass.getDeclaredFields();
      for (final Field field : fieldList) {
        if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
          levelDefinition = levelDefinition + field.getName() + ",";
        }
      }
      objectClass = objectClass.getSuperclass();
    }

    if (!levelDefinition.isEmpty()) {
      levelDefinition = levelDefinition.substring(0, levelDefinition.length() - 1);
    }
    map.put(FULL_LEVEL, levelDefinition);
    return levelDefinition;
  }
コード例 #27
0
  /** Sets the access flag of a member */
  @Override
  protected void setAccessFlag(final Member m) {
    final int mods = m.getModifiers();
    final Class c = m.getDeclaringClass();
    final int cmods = c.getModifiers();
    final String pkg = this.importationManager.getCurrentPackage();
    final String mp = getPackageName(c);
    final boolean samePkg = pkg.equals(mp);

    if (Modifier.isPublic(cmods) || samePkg) {
      if (Modifier.isPublic(mods)) {
        ((AccessibleObject) m).setAccessible(true);
      } else if (Modifier.isProtected(mods)) {
        if (c.isAssignableFrom(this.declaringClass.getSuperclass()) || samePkg) {
          ((AccessibleObject) m).setAccessible(true);
        }
      } else if (!Modifier.isPrivate(mods)) {
        if (samePkg) {
          ((AccessibleObject) m).setAccessible(true);
        }
      } else {
        if (this.declaringClass == c || isInnerClass(this.declaringClass, c)) {
          ((AccessibleObject) m).setAccessible(true);
        }
      }
    }
  }
コード例 #28
0
  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);
  }
コード例 #29
0
ファイル: TestHarFileSystem.java プロジェクト: imace/hops
  @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
  /**
   * 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;
  }