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

InvokerBytecodeGenerator.java 文件源码 项目:openjdk-jdk10 阅读 32 收藏 0 点赞 0 评论 0
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;
}
NonPublicProxyClass.java 文件源码 项目:jdk8u-jdk 阅读 60 收藏 0 点赞 0 评论 0
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);
}
JsUtilityTest.java 文件源码 项目:Selenium-Foundation 阅读 45 收藏 0 点赞 0 评论 0
@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();
    }
}
LuaMapping.java 文件源码 项目:Cubes 阅读 31 收藏 0 点赞 0 评论 0
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);
  }
}
ObjectStreamClass.java 文件源码 项目:OpenJSharp 阅读 43 收藏 0 点赞 0 评论 0
/**
 * 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;
    }
}
ReflectUtils.java 文件源码 项目:dubbox-hystrix 阅读 46 收藏 0 点赞 0 评论 0
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;
}
CommonNameResolver$AccessibleObjectResolver.java 文件源码 项目:boohee_v5.6 阅读 42 收藏 0 点赞 0 评论 0
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();
}
MemberUtils.java 文件源码 项目:DroidTelescope 阅读 41 收藏 0 点赞 0 评论 0
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;
}
BaseQuickAdapter.java 文件源码 项目:garras 阅读 48 收藏 0 点赞 0 评论 0
/**
 * 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;
}
PatchByteCodeTest.java 文件源码 项目:incubator-netbeans 阅读 39 收藏 0 点赞 0 评论 0
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);
}
SteamGson.java 文件源码 项目:Java--Steam-Loader 阅读 88 收藏 0 点赞 0 评论 0
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();
    }
LocatableAnnotation.java 文件源码 项目:OpenJSharp 阅读 37 收藏 0 点赞 0 评论 0
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;
    }
}
InvocationTemplate.java 文件源码 项目:jsf-sdk 阅读 33 收藏 0 点赞 0 评论 0
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;
}
ReflectUtils.java 文件源码 项目:EatDubbo 阅读 47 收藏 0 点赞 0 评论 0
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;
}
FieldsScanner.java 文件源码 项目:openjdk-jdk10 阅读 50 收藏 0 点赞 0 评论 0
/**
 * 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();
    }
}
mxObjectCodec.java 文件源码 项目:Tarski 阅读 54 收藏 0 点赞 0 评论 0
/**
 * 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;
}
PlainOldDataReadonlyVisitor.java 文件源码 项目:cdep 阅读 33 收藏 0 点赞 0 评论 0
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);
    }
  }
}
Messages.java 文件源码 项目:cr-private-server 阅读 49 收藏 0 点赞 0 评论 0
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);
}
PluginLoader.java 文件源码 项目:shuffleboard 阅读 47 收藏 0 点赞 0 评论 0
/**
 * 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;
}
ExtensionTransformer.java 文件源码 项目:manifold 阅读 39 收藏 0 点赞 0 评论 0
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;
}
ObjectStreamClass_1_3_1.java 文件源码 项目:OpenJSharp 阅读 47 收藏 0 点赞 0 评论 0
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;
}
RuntimeClassInfoImpl.java 文件源码 项目:openjdk-jdk10 阅读 38 收藏 0 点赞 0 评论 0
@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 );
}
EntityHelper.java 文件源码 项目:azeroth 阅读 57 收藏 0 点赞 0 评论 0
/**
 * 获取全部的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;
}
ReflectUtils.java 文件源码 项目:dubbox-hystrix 阅读 48 收藏 0 点赞 0 评论 0
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;
  }
UtilityClassAssertions.java 文件源码 项目:tokamak 阅读 90 收藏 0 点赞 0 评论 0
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;
}
NashornScriptEngine.java 文件源码 项目:openjdk-jdk10 阅读 36 收藏 0 点赞 0 评论 0
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;
}
CallerSensitiveDynamicMethod.java 文件源码 项目:OpenJSharp 阅读 36 收藏 0 点赞 0 评论 0
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);
}
Solution.java 文件源码 项目:JavaRushTasks 阅读 53 收藏 0 点赞 0 评论 0
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
}
ReflectionSubstitutions.java 文件源码 项目:openjdk-jdk10 阅读 42 收藏 0 点赞 0 评论 0
@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);
    }
}
RADVisualContainer.java 文件源码 项目:incubator-netbeans 阅读 41 收藏 0 点赞 0 评论 0
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;
}


问题


面经


文章

微信
公众号

扫码关注公众号