Java Code Examples for java.lang.reflect.Modifier

The following are top voted examples for showing how to use java.lang.reflect.Modifier. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: InvokerBytecodeGenerator.java   View source code 7 votes vote down vote up
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;
}
 
Example 2
Project: jdk8u-jdk   File: NonPublicProxyClass.java   View source code 7 votes vote down vote up
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);
}
 
Example 3
Project: Selenium-Foundation   File: JsUtilityTest.java   View source code 7 votes vote down vote up
@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();
    }
}
 
Example 4
Project: Cubes   File: LuaMapping.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 5
Project: OpenJSharp   File: ObjectStreamClass.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 6
Project: dubbox-hystrix   File: ReflectUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: boohee_v5.6   File: CommonNameResolver$AccessibleObjectResolver.java   View source code 6 votes vote down vote up
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();
}
 
Example 8
Project: DroidTelescope   File: MemberUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 9
Project: garras   File: BaseQuickAdapter.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: incubator-netbeans   File: PatchByteCodeTest.java   View source code 6 votes vote down vote up
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);
}
 
Example 11
Project: Java--Steam-Loader   File: SteamGson.java   View source code 6 votes vote down vote up
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();
    }
 
Example 12
Project: OpenJSharp   File: LocatableAnnotation.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 13
Project: jsf-sdk   File: InvocationTemplate.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: EatDubbo   File: ReflectUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: openjdk-jdk10   File: FieldsScanner.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 16
Project: Tarski   File: mxObjectCodec.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Project: cdep   File: PlainOldDataReadonlyVisitor.java   View source code 6 votes vote down vote up
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);
    }
  }
}
 
Example 18
Project: cr-private-server   File: Messages.java   View source code 6 votes vote down vote up
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);
}
 
Example 19
Project: shuffleboard   File: PluginLoader.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 20
Project: manifold   File: ExtensionTransformer.java   View source code 6 votes vote down vote up
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;
}
 
Example 21
Project: OpenJSharp   File: ObjectStreamClass_1_3_1.java   View source code 6 votes vote down vote up
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;
}
 
Example 22
Project: openjdk-jdk10   File: RuntimeClassInfoImpl.java   View source code 6 votes vote down vote up
@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 );
}
 
Example 23
Project: azeroth   File: EntityHelper.java   View source code 6 votes vote down vote up
/**
 * 获取全部的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;
}
 
Example 24
Project: dubbox-hystrix   File: ReflectUtils.java   View source code 6 votes vote down vote up
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;
  }
 
Example 25
Project: tokamak   File: UtilityClassAssertions.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: openjdk-jdk10   File: NashornScriptEngine.java   View source code 6 votes vote down vote up
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;
}
 
Example 27
Project: OpenJSharp   File: CallerSensitiveDynamicMethod.java   View source code 5 votes vote down vote up
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);
}
 
Example 28
Project: JavaRushTasks   File: Solution.java   View source code 5 votes vote down vote up
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
}
 
Example 29
Project: openjdk-jdk10   File: ReflectionSubstitutions.java   View source code 5 votes vote down vote up
@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);
    }
}
 
Example 30
Project: incubator-netbeans   File: RADVisualContainer.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: jkami   File: SqlUtils.java   View source code 5 votes vote down vote up
/**
 * 获得属性和注解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;
}
 
Example 32
Project: ibm-cos-sdk-java   File: ReflectionUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 33
Project: Java-EX   File: FunctionInterfaceUtil.java   View source code 5 votes vote down vote up
/**
 * 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];
}
 
Example 34
Project: Jenisys3   File: SimpleConfig.java   View source code 5 votes vote down vote up
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;
}
 
Example 35
Project: lams   File: EntityClass.java   View source code 5 votes vote down vote up
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 "
		);
	}
}
 
Example 36
Project: jdk8u-jdk   File: XObjectInputStream.java   View source code 5 votes vote down vote up
/****************************************************************/

    /* 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;
    }
 
Example 37
Project: manifold   File: ExtCodeGen.java   View source code 5 votes vote down vote up
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 );
}
 
Example 38
Project: UtilsVerifier   File: UtilsVerifier.java   View source code 5 votes vote down vote up
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());
        }
    }
}
 
Example 39
Project: RxJava3-preview   File: OperatorsAreFinal.java   View source code 5 votes vote down vote up
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());
    }
}
 
Example 40
Project: gitplex-mit   File: BeanUtils.java   View source code 5 votes vote down vote up
/**
 * 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;
	}
}