Java 类java.lang.reflect.Modifier 实例源码

项目:openjdk-jdk10    文件:InvokerBytecodeGenerator.java   
static boolean isStaticallyNameable(Class<?> cls) {
    if (cls == Object.class)
        return true;
    while (cls.isArray())
        cls = cls.getComponentType();
    if (cls.isPrimitive())
        return true;  // int[].class, for example
    if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
        return false;
    // could use VerifyAccess.isClassAccessible but the following is a safe approximation
    if (cls.getClassLoader() != Object.class.getClassLoader())
        return false;
    if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
        return true;
    if (!Modifier.isPublic(cls.getModifiers()))
        return false;
    for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
        if (VerifyAccess.isSamePackage(pkgcls, cls))
            return true;
    }
    return false;
}
项目:jdk8u-jdk    文件:NonPublicProxyClass.java   
public void run() throws Exception {
    boolean hasAccess = loader != null || hasAccess();
    try {
        proxyClass = Proxy.getProxyClass(loader, interfaces);
        if (!hasAccess) {
            throw new RuntimeException("should have no permission to create proxy class");
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != RuntimePermission.class ||
                !e.getPermission().getName().equals("getClassLoader")) {
            throw e;
        }
        return;
    }

    if (Modifier.isPublic(proxyClass.getModifiers())) {
        throw new RuntimeException(proxyClass + " must be non-public");
    }
    newProxyInstance();
    newInstanceFromConstructor(proxyClass);
}
项目:Selenium-Foundation    文件:JsUtilityTest.java   
@NoDriver
@Test(expectedExceptions = {AssertionError.class},
        expectedExceptionsMessageRegExp = "JsUtility is a static utility class that cannot be instantiated")
public void testPrivateConstructor() throws Throwable {

    Constructor<?>[] ctors;
    ctors = JsUtility.class.getDeclaredConstructors();
    assertEquals(ctors.length, 1, "JsUtility must have exactly one constructor");
    assertEquals(ctors[0].getModifiers() & Modifier.PRIVATE, Modifier.PRIVATE,
                    "JsUtility constructor must be private");
    assertEquals(ctors[0].getParameterTypes().length, 0, "JsUtility constructor must have no arguments");

    try {
        ctors[0].setAccessible(true);
        ctors[0].newInstance();
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
项目:Cubes    文件:LuaMapping.java   
public static LuaTable mapping(Class<?> c) {
  try {
    LuaTable luaTable = new LuaTable();
    for (Field field : c.getFields()) {
      if (!Modifier.isStatic(field.getModifiers())) continue;
      if (LuaValue.class.isAssignableFrom(field.getType())) {
        luaTable.set(field.getName(), (LuaValue) field.get(null));
      }
      if (field.getType().equals(Class.class)) {
        luaTable.set(field.getName(), mapping((Class<?>) field.get(null)));
      }
    }
    return new ReadOnlyLuaTable(luaTable);
  } catch (Exception e) {
    throw new CubesException("Failed to create lua api", e);
  }
}
项目:OpenJSharp    文件:ObjectStreamClass.java   
/**
 * Returns non-static private method with given signature defined by given
 * class, or null if none found.  Access checks are disabled on the
 * returned method (if any).
 */
private static Method getPrivateMethod(Class<?> cl, String name,
                                       Class<?>[] argTypes,
                                       Class<?> returnType)
{
    try {
        Method meth = cl.getDeclaredMethod(name, argTypes);
        meth.setAccessible(true);
        int mods = meth.getModifiers();
        return ((meth.getReturnType() == returnType) &&
                ((mods & Modifier.STATIC) == 0) &&
                ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
项目:dubbox-hystrix    文件:ReflectUtils.java   
public static Map<String, Field> getBeanPropertyFields(Class cl) {
    Map<String, Field> properties = new HashMap<String, Field>();
    for(; cl != null; cl = cl.getSuperclass()) {
        Field[] fields = cl.getDeclaredFields();
        for(Field field : fields) {
            if (Modifier.isTransient(field.getModifiers())
                || Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            field.setAccessible(true);

            properties.put(field.getName(), field);
        }
    }

    return properties;
}
项目:boohee_v5.6    文件:CommonNameResolver$AccessibleObjectResolver.java   
public String resolve(IObject obj) throws SnapshotException {
    StringBuilder r = new StringBuilder();
    ISnapshot snapshot = obj.getSnapshot();
    Object val = obj.resolveValue("modifiers");
    if (val instanceof Integer) {
        r.append(Modifier.toString(((Integer) val).intValue()));
        if (r.length() > 0) {
            r.append(' ');
        }
    }
    IObject ref = (IObject) obj.resolveValue("clazz");
    if (ref == null) {
        return null;
    }
    addClassName(snapshot, ref.getObjectAddress(), r);
    return r.toString();
}
项目:DroidTelescope    文件:MemberUtils.java   
static boolean setAccessibleWorkaround(final AccessibleObject o) {
    if (o == null || o.isAccessible()) {
        return false;
    }
    final Member m = (Member) o;
    if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m
            .getDeclaringClass().getModifiers())) {
        try {
            o.setAccessible(true);
            return true;
        } catch (final SecurityException e) { // NOPMD
            // ignore in favor of subsequent IllegalAccessException
        }
    }
    return false;
}
项目:garras    文件:BaseQuickAdapter.java   
/**
 * try to create Generic K instance
 *
 * @param z
 * @param view
 * @return
 */
@SuppressWarnings("unchecked")
private K createGenericKInstance(Class z, View view) {
    try {
        Constructor constructor;
        // inner and unstatic class
        if (z.isMemberClass() && !Modifier.isStatic(z.getModifiers())) {
            constructor = z.getDeclaredConstructor(getClass(), View.class);
            constructor.setAccessible(true);
            return (K) constructor.newInstance(this, view);
        } else {
            constructor = z.getDeclaredConstructor(View.class);
            constructor.setAccessible(true);
            return (K) constructor.newInstance(view);
        }
    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
        Timber.e(e);
    }
    return null;
}
项目:incubator-netbeans    文件:PatchByteCodeTest.java   
public void testPatchingPublic() throws Exception {
    Class<?> c = new L().loadClass(C.class.getName());
    assertNotSame(c, C.class);
    Member m;
    m = c.getDeclaredConstructor(boolean.class);
    assertEquals(0, m.getModifiers() & Modifier.PUBLIC);
    assertEquals(Modifier.PRIVATE, m.getModifiers() & Modifier.PRIVATE);
    m = c.getDeclaredConstructor(int.class);
    assertEquals(Modifier.PUBLIC, m.getModifiers() & Modifier.PUBLIC);
    assertEquals(0, m.getModifiers() & Modifier.PRIVATE);
    m = c.getDeclaredMethod("m1");
    assertEquals(0, m.getModifiers() & Modifier.PUBLIC);
    assertEquals(Modifier.PRIVATE, m.getModifiers() & Modifier.PRIVATE);
    m = c.getDeclaredMethod("m2");
    assertEquals(Modifier.PUBLIC, m.getModifiers() & Modifier.PUBLIC);
    assertEquals(0, m.getModifiers() & Modifier.PRIVATE);
}
项目:Java--Steam-Loader    文件:SteamGson.java   
public static Gson buildGson() {

        final GsonBuilder gson = new GsonBuilder();

        //gson.setPrettyPrinting();
        gson.serializeNulls();
        gson.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE);

        // register the type adapter factories
        final TypeAdapterFactoryCreator creator = new TypeAdapterFactoryCreator();
        for (final TypeAdapterFactory factory : creator.getAdapters()) {
            gson.registerTypeAdapterFactory(factory);
        }

        return gson.create();
    }
项目:OpenJSharp    文件:LocatableAnnotation.java   
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        if(method.getDeclaringClass()==Locatable.class)
            return method.invoke(this,args);
        if(Modifier.isStatic(method.getModifiers()))
            // malicious code can pass in a static Method object.
            // doing method.invoke() would end up executing it,
            // so we need to protect against it.
            throw new IllegalArgumentException();

        return method.invoke(core,args);
    } catch (InvocationTargetException e) {
        if(e.getTargetException()!=null)
            throw e.getTargetException();
        throw e;
    }
}
项目:jsf-sdk    文件:InvocationTemplate.java   
private Map<String,String> checkArgMatch(Invocation v, Object[] args){
    Map<String, String> result = new HashMap<String, String>();
    String argsType[] = v.getArgsType();
    if(argsType == null || argsType.length == 0){
        return result;
    }
    Class<?> argClasses[] = v.getArgClasses();
    for(int i = 0; i < argsType.length; i++){
        if(args[i] == null || (argClasses != null && (argClasses[i].isPrimitive() || Modifier.isFinal(argClasses[i].getModifiers())))){
            continue;
        }
        Class<?> realClass = args[i].getClass();
        if(!argClasses[i].equals(realClass)){
            String argType = ClassTypeUtils.getTypeStr(realClass);
            result.put(String.valueOf(i), argType);
        }
    }
    return result;
}
项目:EatDubbo    文件:ReflectUtils.java   
public static Map<String, Field> getBeanPropertyFields(Class cl) {
    Map<String, Field> properties = new HashMap<String, Field>();
    for(; cl != null; cl = cl.getSuperclass()) {
        Field[] fields = cl.getDeclaredFields();
        for(Field field : fields) {
            if (Modifier.isTransient(field.getModifiers())
                || Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            field.setAccessible(true);

            properties.put(field.getName(), field);
        }
    }

    return properties;
}
项目:openjdk-jdk10    文件:FieldsScanner.java   
/**
 * Scans the fields in a class hierarchy.
 *
 * @param clazz the class at which to start scanning
 * @param endClazz scanning stops when this class is encountered (i.e. {@code endClazz} is not
 *            scanned)
 */
public void scan(Class<?> clazz, Class<?> endClazz, boolean includeTransient) {
    Class<?> currentClazz = clazz;
    while (currentClazz != endClazz) {
        for (Field field : currentClazz.getDeclaredFields()) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if (!includeTransient && Modifier.isTransient(field.getModifiers())) {
                continue;
            }
            long offset = calc.getOffset(field);
            scanField(field, offset);
        }
        currentClazz = currentClazz.getSuperclass();
    }
}
项目:Tarski    文件:mxObjectCodec.java   
/**
 * Returns the value of the field with the specified name in the specified object instance.
 */
protected Object getFieldValue(Object obj, String fieldname) {
  Object value = null;

  if (obj != null && fieldname != null) {
    Field field = getField(obj, fieldname);

    try {
      if (field != null) {
        if (Modifier.isPublic(field.getModifiers())) {
          value = field.get(obj);
        } else {
          value = getFieldValueWithAccessor(obj, field);
        }
      }
    } catch (IllegalAccessException e1) {
      value = getFieldValueWithAccessor(obj, field);
    } catch (Exception e) {
      // ignore
    }
  }

  return value;
}
项目:cdep    文件:PlainOldDataReadonlyVisitor.java   
private void visitFields(@NotNull Object node) {
  if (node.getClass().isEnum()) {
    return;
  }
  for (Field field : node.getClass().getFields()) {
    if (Modifier.isStatic(field.getModifiers())) {
      continue;
    }
    require(!Objects.equals(field.getDeclaringClass(), Object.class));
    require(!Objects.equals(field.getDeclaringClass(), String.class));
    String methodName = getVisitorName(field.getType());
    Method method = getMethod(getClass(), methodName, String.class, field.getType());
    Object fieldValue = getFieldValue(field, node);
    if (fieldValue != null) {
      invoke(method, this, field.getName(), fieldValue);
    }
  }
}
项目:cr-private-server    文件:Messages.java   
private static Map<Short, String> createMap() {
    Map<Short, String> map = new HashMap<>();

    for (Field field : Messages.class.getFields()) {
        int modifiers = field.getModifiers();
        if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && field.getType() == short.class) {
            try {
                map.put(field.getShort(null), field.getName());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    return Collections.unmodifiableMap(map);
}
项目:shuffleboard    文件:PluginLoader.java   
/**
 * Attempts to load a plugin class. This class may or not be a plugin; only a plugin class will be loaded. A plugin
 * loaded with this method will be loaded after unloading a plugin that shares the same
 * {@link Plugin#idString() ID string}, if one exists.
 *
 * @param clazz the class to attempt to load
 *
 * @return true if the class is a plugin class and was successfully loaded; false otherwise
 */
public boolean loadPluginClass(Class<? extends Plugin> clazz) {
  if (Plugin.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
    try {
      Plugin.validatePluginClass(clazz);
      if (Modifier.isPublic(clazz.getConstructor().getModifiers())) {
        Plugin plugin = clazz.newInstance();
        load(plugin);
        return true;
      }
    } catch (ReflectiveOperationException | InvalidPluginDefinitionException e) {
      log.log(Level.WARNING, "Could not load plugin class", e);
      return false;
    }
  }
  return false;
}
项目:manifold    文件:ExtensionTransformer.java   
private boolean isStructuralMethod( JCTree.JCMethodInvocation tree )
{
  JCExpression methodSelect = tree.getMethodSelect();
  if( methodSelect instanceof JCTree.JCFieldAccess )
  {
    JCTree.JCFieldAccess m = (JCTree.JCFieldAccess)methodSelect;
    if( m.sym != null && !m.sym.getModifiers().contains( javax.lang.model.element.Modifier.STATIC ) )
    {
      JCExpression thisArg = m.selected;
      if( TypeUtil.isStructuralInterface( _tp, thisArg.type.tsym ) )
      {
        return true;
      }
    }
  }
  return false;
}
项目:OpenJSharp    文件:ObjectStreamClass_1_3_1.java   
static MethodSignature[] removePrivateAndSort(Member[] m) {
    int numNonPrivate = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            numNonPrivate++;
        }
    }
    MethodSignature[] cm = new MethodSignature[numNonPrivate];
    int cmi = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            cm[cmi] = new MethodSignature(m[i]);
            cmi++;
        }
    }
    if (cmi > 0)
        Arrays.sort(cm, cm[0]);
    return cm;
}
项目:openjdk-jdk10    文件:RuntimeClassInfoImpl.java   
@Override
protected RuntimePropertySeed createFieldSeed(Field field) {
   final boolean readOnly = Modifier.isStatic(field.getModifiers());
    Accessor acc;
    try {
        if (supressAccessorWarnings) {
            acc = ((InternalAccessorFactory)accessorFactory).createFieldAccessor(clazz, field, readOnly, supressAccessorWarnings);
        } else {
            acc = accessorFactory.createFieldAccessor(clazz, field, readOnly);
        }
    } catch(JAXBException e) {
        builder.reportError(new IllegalAnnotationException(
                Messages.CUSTOM_ACCESSORFACTORY_FIELD_ERROR.format(
                nav().getClassName(clazz), e.toString()), this ));
        acc = Accessor.getErrorInstance(); // error recovery
    }
    return new RuntimePropertySeed(super.createFieldSeed(field), acc );
}
项目:azeroth    文件:EntityHelper.java   
/**
 * 获取全部的Field
 *
 * @param entityClass
 * @param fieldList
 * @return
 */
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
    if (fieldList == null) {
        fieldList = new ArrayList<Field>();
    }
    if (entityClass.equals(Object.class)) {
        return fieldList;
    }
    Field[] fields = entityClass.getDeclaredFields();
    for (Field field : fields) {
        // 排除静态字段
        if (!Modifier.isStatic(field.getModifiers())) {
            fieldList.add(field);
        }
    }
    Class<?> superClass = entityClass.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)
            && (!Map.class.isAssignableFrom(superClass)
            && !Collection.class.isAssignableFrom(superClass))) {
        return getAllField(entityClass.getSuperclass(), fieldList);
    }
    return fieldList;
}
项目:dubbox-hystrix    文件:ReflectUtils.java   
public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException {
    Constructor<?> targetConstructor;
try {
    targetConstructor = clazz.getConstructor(new Class<?>[] {paramType});
} catch (NoSuchMethodException e) {
    targetConstructor = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
        if (Modifier.isPublic(constructor.getModifiers()) 
                && constructor.getParameterTypes().length == 1
                && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
            targetConstructor = constructor;
            break;
        }
    }
    if (targetConstructor == null) {
        throw e;
    }
}
return targetConstructor;
  }
项目:tokamak    文件:UtilityClassAssertions.java   
public UtilityClassAssertions isAWellDefinedUtilityClass() {
    Assertions.assertThat(Modifier.isFinal(actual.getModifiers())).describedAs("A utility class should be marked as final.").isTrue();
    Assertions.assertThat(actual.getDeclaredConstructors().length).describedAs("A utility class should only have one constructor, but this class has " + actual.getDeclaredConstructors().length).isEqualTo(1);

    try {
        Constructor<?> constructor = actual.getDeclaredConstructor();
        if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) {
            Assertions.fail("The constructor is not private.");
        }

        constructor.setAccessible(true);
        constructor.newInstance();
        constructor.setAccessible(false);

        for (Method method : actual.getMethods()) {
            if (!Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass().equals(actual)) {
                Assertions.fail("A utility class should not have instance methods, but found: " + method);
            }
        }
    }
    catch (Exception e) {
        Assertions.fail("An error occurred while inspecting the class.");
    }

    return this;
}
项目:openjdk-jdk10    文件:NashornScriptEngine.java   
private static boolean isInterfaceImplemented(final Class<?> iface, final ScriptObject sobj) {
    for (final Method method : iface.getMethods()) {
        // ignore methods of java.lang.Object class
        if (method.getDeclaringClass() == Object.class) {
            continue;
        }

        // skip check for default methods - non-abstract, interface methods
        if (! Modifier.isAbstract(method.getModifiers())) {
            continue;
        }

        final Object obj = sobj.get(method.getName());
        if (! (obj instanceof ScriptFunction)) {
            return false;
        }
    }
    return true;
}
项目:OpenJSharp    文件:CallerSensitiveDynamicMethod.java   
private static MethodType getMethodType(final AccessibleObject ao) {
    final boolean isMethod = ao instanceof Method;
    final Class<?> rtype = isMethod ? ((Method)ao).getReturnType() : ((Constructor<?>)ao).getDeclaringClass();
    final Class<?>[] ptypes = isMethod ? ((Method)ao).getParameterTypes() : ((Constructor<?>)ao).getParameterTypes();
    final MethodType type = MethodType.methodType(rtype, ptypes);
    final Member m = (Member)ao;
    return type.insertParameterTypes(0,
            isMethod ?
                    Modifier.isStatic(m.getModifiers()) ?
                            Object.class :
                            m.getDeclaringClass() :
                    StaticClass.class);
}
项目:JavaRushTasks    文件:Solution.java   
public static void main(String[] args) {
    int modifiersOfThisClass = Solution.class.getModifiers();
    System.out.println(isAllModifiersContainSpecificModifier(modifiersOfThisClass, Modifier.PUBLIC));   //true
    System.out.println(isAllModifiersContainSpecificModifier(modifiersOfThisClass, Modifier.STATIC));   //false

    int modifiersOfMethod = getMainMethod().getModifiers();
    System.out.println(isAllModifiersContainSpecificModifier(modifiersOfMethod, Modifier.STATIC));      //true
}
项目:openjdk-jdk10    文件:ReflectionSubstitutions.java   
@MethodSubstitution
public static int getClassAccessFlags(Class<?> aClass) {
    KlassPointer klass = ClassGetHubNode.readClass(GraalDirectives.guardingNonNull(aClass));
    if (klass.isNull()) {
        // Class for primitive type
        return Modifier.ABSTRACT | Modifier.FINAL | Modifier.PUBLIC;
    } else {
        return klass.readInt(klassAccessFlagsOffset(INJECTED_VMCONFIG), KLASS_ACCESS_FLAGS_LOCATION) & jvmAccWrittenFlags(INJECTED_VMCONFIG);
    }
}
项目:incubator-netbeans    文件:RADVisualContainer.java   
public static boolean sameLayouts(Class layoutClass1, Class layoutClass2) {
    if (layoutClass2 == layoutClass1) {
        return true; // incl. both null
    } else if (layoutClass1 != null && layoutClass2 != null) {
        return layoutClass2.getName().equals(layoutClass1.getName())
               || (layoutClass2.isAssignableFrom(layoutClass1)
                   && (layoutClass1.getModifiers()&Modifier.PUBLIC) == 0) // e.g. JRootPane$1 should be same as BorderLayout
               || (layoutClass1.isAssignableFrom(layoutClass2)
                   && (layoutClass2.getModifiers()&Modifier.PUBLIC) == 0) // e.g. JRootPane$1 should be same as BorderLayout
               || (SwingLayoutBuilder.isRelevantLayoutManager(layoutClass1.getName())
                   && SwingLayoutBuilder.isRelevantLayoutManager(layoutClass2.getName()));
    }
    return false;
}
项目:jkami    文件:SqlUtils.java   
/**
 * 获得属性和注解map
 * 
 * @param clazz
 *            class
 * @return key属性 value注解
 */
public static Map<String, String> getEntityFiledColumnMap(Class<?> clazz) {
    String kname = clazz.getName();
    String k = kname + "#filedColMap#";
    if (mapCache.containsKey(k)) {
        return (Map<String, String>) mapCache.get(k);
    }
    Map<String, String> mp = new LinkedCaseInsensitiveMap<>();
    List<Field> lsField = JkBeanUtils.getAllFields(clazz);
    for (Field field : lsField) {
        // 排除静态
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        String fieldName = field.getName();
        if (fieldName.indexOf("CGLIB") > -1) {
            continue;
        }
        Sql Sql = getAnnotation(field,Sql.class);
        if (Sql != null) {
            continue;
        }
        String columnString;
        Column column = getAnnotation(field,Column.class);
        if (column != null) {
            columnString = column.value();
        } else {
            columnString = JkBeanUtils.columnToHumpReversal(field.getName());
        }
        mp.put(field.getName(), columnString);
    }
    mapCache.put(k, mp);
    return mp;
}
项目:ibm-cos-sdk-java    文件:ReflectionUtils.java   
public static <T> T newInstanceWithAllFieldsSet(Class<T> clz, List<RandomSupplier<?>> suppliers) {
    T instance = newInstance(clz);
    for(Field field: clz.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }

        final Class<?> type = field.getType();
        field.setAccessible(true);

        RandomSupplier<?> supplier = findSupplier(suppliers, type);
        if (supplier != null) {
            setField(instance, field, supplier.getNext());
        } else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) {
            setField(instance, field, Math.abs(RANDOM.nextInt()));
        } else if (type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) {
            setField(instance, field, Math.abs(RANDOM.nextLong()));
        } else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
            Object bool = getField(instance, field);
            if (bool == null) {
                setField(instance, field, RANDOM.nextBoolean());
            } else {
                setField(instance, field, !Boolean.valueOf(bool.toString()));
            }
        } else if (type.isAssignableFrom(String.class)) {
            setField(instance, field, UUID.randomUUID().toString());
        } else {
            throw new RuntimeException(String.format("Could not set value for type %s no supplier available.", type));
        }
    }
    return instance;
}
项目:Java-EX    文件:FunctionInterfaceUtil.java   
/**
 * Get the method from a function interface
 *
 * @param clz
 * @return null if the given class is not a function interface
 */
public static <T> Method getFunctionInterfaceMethod(Class<?> clz) {
  if (!clz.isInterface()) {
    return null;
  }
  Method[] ms = Stream.of(clz.getMethods())
      .filter(m -> !(m.isDefault() || m.isBridge() || m.isSynthetic() || Modifier.isStatic(m.getModifiers())))
      .toArray(Method[]::new);
  if (ms.length != 1) {
    return null;
  }
  return ms[0];
}
项目:Jenisys3    文件:SimpleConfig.java   
private String getPath(Field field) {
    String path = null;
    if (field.isAnnotationPresent(Path.class)) {
        Path pathDefine = field.getAnnotation(Path.class);
        path = pathDefine.value();
    }
    if (path == null || path.isEmpty()) path = field.getName().replaceAll("_", ".");
    if (Modifier.isFinal(field.getModifiers())) return null;
    if (Modifier.isPrivate(field.getModifiers())) field.setAccessible(true);
    return path;
}
项目:lams    文件:EntityClass.java   
private void validateMethod(MethodInfo methodInfo,
                            Class callbackTypeClass,
                            Map<Class<?>, String> callbacksByClass,
                            boolean isListener) {
    if ( methodInfo.returnType().kind() != Kind.VOID ) {
        throw new PersistenceException( "Callback method " + methodInfo.name() + " must have a void return type in " );
    }
    if ( Modifier.isStatic( methodInfo.flags() ) || Modifier.isFinal( methodInfo.flags() ) ) {
        throw new PersistenceException( "Callback method " + methodInfo.name() + " must not be static or final in " );
    }
    Type[] argTypes = methodInfo.args();
    if ( isListener ) {
        if ( argTypes.length != 1 ) {
            throw new PersistenceException( "Callback method " + methodInfo.name() + " must have exactly one argument in " );
        }
        String argTypeName = argTypes[0].name().toString();
        if ( !argTypeName.equals( Object.class.getName() ) && !argTypeName.equals( getName() ) ) {
            throw new PersistenceException(
                    "The argument for callback method " + methodInfo.name() +
                            " must be defined as either Object or " + getEntityName() + " in "
            );
        }
    }
    else if ( argTypes.length != 0 ) {
        throw new PersistenceException( "Callback method " + methodInfo.name() + " must have no arguments in " );
    }
    if ( callbacksByClass.containsKey( callbackTypeClass ) ) {
        throw new PersistenceException(
                "Only one method may be annotated as a " + callbackTypeClass.getSimpleName() +
                        " callback method in "
        );
    }
}
项目:jdk8u-jdk    文件:XObjectInputStream.java   
/****************************************************************/

    /* CODE LIFTED FROM ObjectStreamClass constuctor.
     * ObjectStreamClass.readObjectMethod is private.
     *
     * Look for the readObject method
     * Set the accessible flag on it here. ObjectOutputStream
     * will call it as necessary.
     */
    static public Method getReadObjectMethod(final Class cl) {

        Method readObjectMethod = (Method)
            java.security.AccessController.doPrivileged
            (new java.security.PrivilegedAction() {
                public Object run() {
                    Method m = null;
                    try {
                        Class[] args = {ObjectInputStream.class};
                        m = cl.getDeclaredMethod("readObject", args);
                        int mods = m.getModifiers();
                        // Method must be private and non-static
                        if (!Modifier.isPrivate(mods) ||
                            Modifier.isStatic(mods)) {
                            m = null;
                        } else {
                            m.setAccessible(true);
                        }
                    } catch (NoSuchMethodException e) {
                        m = null;
                    }
                    return m;
                }
            });
        return readObjectMethod;
    }
项目:manifold    文件:ExtCodeGen.java   
private boolean isExtensionMethod( AbstractSrcMethod method, SrcClass extendedType )
{
  if( !Modifier.isStatic( (int)method.getModifiers() ) || Modifier.isPrivate( (int)method.getModifiers() ) )
  {
    return false;
  }

  if( method.hasAnnotation( Extension.class ) )
  {
    return true;
  }

  return hasThisAnnotation( method, extendedType );
}
项目:UtilsVerifier    文件:UtilsVerifier.java   
private void hasNoInstanceMethods() {
    if (suppressInstanceMethodCheck) return;
    final Method[] methods = classUnderTest.getDeclaredMethods();
    for (int index = 0; index < methods.length; index++) {
        final Method method = methods[index];
        if (!Modifier.isStatic(method.getModifiers())) {
            throw new AssertionError(classUnderTest.getName()
                    + " contains instance method " + method.getName());
        }
    }
}
项目:RxJava3-preview    文件:OperatorsAreFinal.java   
void check(String baseClassName, String project) throws Exception {
    File f = directoryOf(baseClassName, project);
    if (f == null) {
        return;
    }

    StringBuilder e = new StringBuilder();

    File[] files = f.listFiles();
    if (files != null) {
        for (File g : files) {
            if (g.getName().startsWith(baseClassName) && g.getName().endsWith(".java")) {
                String className = "io.reactivex." + project + ".internal.operators." + g.getName().replace(".java", "");

                Class<?> clazz = Class.forName(className);

                if ((clazz.getModifiers() & Modifier.FINAL) == 0 && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
                    e.append("java.lang.RuntimeException: ").append(className).append(" is not final\r\n");
                    e.append(" at ").append(className).append(" (").append(g.getName()).append(":14)\r\n\r\n");
                }
            }
        }
    }

    if (e.length() != 0) {
        System.out.println(e);

        throw new AssertionError(e.toString());
    }
}
项目:gitplex-mit    文件:BeanUtils.java   
/**
 * Check if specified method is a getter method.
 * <p>
 * @param method
 *          method to be checked
 * @return
 *          whether or not the method represents a getter method
 */
public static boolean isGetter(Method method) {
    if ((method.getName().startsWith("get") || method.getName().startsWith("is")) && 
            !Modifier.isStatic(method.getModifiers()) && method.getParameterTypes().length == 0) {
        return true;
    } else {
        return false;
    }
}