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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
	}
}
 
Example 41
Project: openjdk-jdk10   File: CallerSensitiveDynamicMethod.java   Source Code and License 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 42
Project: Elasticsearch   File: SingleMethodInjector.java   Source Code and License 5 votes vote down vote up
private MethodInvoker createMethodInvoker(final Method method) {

        // We can't use FastMethod if the method is private.
        int modifiers = method.getModifiers();
        if (!Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers)) {
        }

        return new MethodInvoker() {
            @Override
            public Object invoke(Object target, Object... parameters)
                    throws IllegalAccessException, InvocationTargetException {
                return method.invoke(target, parameters);
            }
        };
    }
 
Example 43
Project: incubator-netbeans   File: FormEditorCustomizer.java   Source Code and License 5 votes vote down vote up
private void fireChanged() {
    FormLoaderSettings options = FormLoaderSettings.getInstance();
    boolean isChanged = false;
    if (rbGenerateFields.isSelected()) {
        switch (cbModifier.getSelectedIndex()) {
            case 0:
                isChanged = options.getVariablesModifier() != Modifier.PUBLIC;
                break;
            case 1:
                isChanged = options.getVariablesModifier() != 0;
                break;
            case 2:
                isChanged = options.getVariablesModifier() != Modifier.PROTECTED;
                break;
            case 3:
                isChanged = options.getVariablesModifier() != Modifier.PRIVATE;
                break;
        }
    }
    try {
        changed = isChanged || options.getFoldGeneratedCode() != cbFold.isSelected()
                || options.getAssistantShown() != cbAssistant.isSelected()
                || options.getGenerateFQN() != cbFQN.isSelected()
                || options.getListenerGenerationStyle() != cbListenerStyle.getSelectedIndex()
                || options.getLayoutCodeTarget() != cbLayoutStyle.getSelectedIndex()
                || options.getAutoSetComponentName() != cbComponentNames.getSelectedIndex()
                || options.getI18nAutoMode() != cbAutoI18n.getSelectedIndex()
                || options.getVariablesLocal() != rbGenerateLocals.isSelected()
                || options.getGridX() != (Integer) spGridSize.getValue()
                || options.getGridY() != (Integer) spGridSize.getValue()
                || !options.getGuidingLineColor().equals(guideLineColorProperty.getValue())
                || !options.getSelectionBorderColor().equals(selectionBorderColorProperty.getValue())
                || options.getPaintAdvancedLayoutInfo() != (cbPaintLayout.isSelected() ? 3 : 0);
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 44
Project: OpenJSharp   File: Accessor.java   Source Code and License 5 votes vote down vote up
private void makeAccessible(Method m) {
    if (!Modifier.isPublic(m.getModifiers()) || !Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
        try {
            m.setAccessible(true);
        } catch (SecurityException e) {
            if (!accessWarned)
                // this happens when we don't have enough permission.
                logger.log(Level.WARNING, Messages.UNABLE_TO_ACCESS_NON_PUBLIC_FIELD.format(
                        m.getDeclaringClass().getName(),
                        m.getName()),
                        e);
            accessWarned = true;
        }
    }
}
 
Example 45
Project: jdk8u-jdk   File: ReflectionFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a direct MethodHandle for the {@code writeReplace} method on
 * a serializable class.
 * The single argument of {@link MethodHandle#invoke} is the serializable
 * object.
 *
 * @param cl the Serializable class
 * @return  a direct MethodHandle for the {@code writeReplace} method of the class or
 *          {@code null} if the class does not have a {@code writeReplace} method
 */
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
                                                       String methodName) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            Method m = defCl.getDeclaredMethod(methodName);
            if (m.getReturnType() != Object.class) {
                return null;
            }
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
                return null;
            } else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
                // fall through
            } else if (Modifier.isPrivate(mods) && (cl != defCl)) {
                return null;
            } else if (!packageEquals(cl, defCl)) {
                return null;
            }
            try {
                // Normal return
                m.setAccessible(true);
                return MethodHandles.lookup().unreflect(m);
            } catch (IllegalAccessException ex0) {
                // setAccessible should prevent IAE
                throw new InternalError("Error", ex0);
            }
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }
    return null;
}
 
Example 46
Project: lams   File: BeanProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the default constructor, or null if none is found
 * 
 * @param type
 * @deprecated As of 1.4.6 use {@link #newInstance(Class)} or {@link #canInstantiate(Class)} directly.
 */
@Deprecated
protected Constructor<?> getDefaultConstrutor(final Class<?> type) {

    final Constructor<?>[] constructors = type.getConstructors();
    for (final Constructor<?> c : constructors) {
        if (c.getParameterTypes().length == 0 && Modifier.isPublic(c.getModifiers())) {
            return c;
        }
    }
    return null;
}
 
Example 47
Project: sierra   File: CodonTranslationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConstructor() throws Exception {
	Constructor<CodonTranslation> constructor = CodonTranslation.class.getDeclaredConstructor();
	assertTrue(Modifier.isPrivate(constructor.getModifiers()));
	constructor.setAccessible(true);
	constructor.newInstance();
}
 
Example 48
Project: reflect   File: Example.java   Source Code and License 5 votes vote down vote up
private static void constructors() {
  Constructors cs1 = Scanner.paths("/io/ytcode/reflect/").scan().classes().constructors();

  Constructors cs2 =
      cs1.filter(
          new Predicate<Constructor<?>>() {
            @Override
            public boolean apply(Constructor<?> input) {
              return Invokable.from(input).isPublic();
            }
          });
  System.out.println(cs2);

  Constructors cs3 = cs1.modifiers(Modifier.PUBLIC);
  System.out.println(cs3);
}
 
Example 49
Project: dubbocloud   File: AbstractConfig.java   Source Code and License 5 votes vote down vote up
protected static void appendAttributes(Map<Object, Object> parameters, Object config, String prefix) {
    if (config == null) {
        return;
    }
    Method[] methods = config.getClass().getMethods();
    for (Method method : methods) {
        try {
            String name = method.getName();
            if ((name.startsWith("get") || name.startsWith("is")) 
                    && ! "getClass".equals(name)
                    && Modifier.isPublic(method.getModifiers()) 
                    && method.getParameterTypes().length == 0
                    && isPrimitive(method.getReturnType())) {
                Parameter parameter = method.getAnnotation(Parameter.class);
                if (parameter == null || !parameter.attribute())
                    continue;
                String key;
                if (parameter != null && parameter.key() != null && parameter.key().length() > 0) {
                    key = parameter.key();
                } else {
                    int i = name.startsWith("get") ? 3 : 2;
                    key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
                }
                Object value = method.invoke(config, new Object[0]);
                if (value != null) {
                    if (prefix != null && prefix.length() > 0) {
                        key = prefix + "." + key;
                    }
                    parameters.put(key, value);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
 
Example 50
Project: openjdk-jdk10   File: CaptureTest.java   Source Code and License 5 votes vote down vote up
public Tester makeLocal(final String message) {
    class LocalTester extends Tester {
        public LocalTester(final int localparam) {
            super(localparam);
        }

        protected String[] names() {
            return new String[] {
                "this$1",
                "localparam",
                "val$message"
            };
        }

        protected int[] modifiers() {
            return new int[] {
                Modifier.FINAL | MANDATED,
                Modifier.FINAL,
                Modifier.FINAL | SYNTHETIC
            };
        }

        protected Class[] types() {
            return new Class[] {
                Encloser.class,
                int.class,
                String.class
            };
        }

        public String message() {
            return message;
        }
    }

    return new LocalTester(2);
}
 
Example 51
Project: MaxSim   File: ObjectReader.java   Source Code and License 5 votes vote down vote up
public void doDouble(DoubleField field, boolean isVMField) {
   java.lang.reflect.Field f = null;
   try {
      f = readField(field);
      if (Modifier.isFinal(f.getModifiers())) return;
      f.setAccessible(true);
      f.setDouble(obj, field.getValue(getObj()));
   } catch (Exception ex) {
      printFieldSetError(f, ex);
   }
}
 
Example 52
Project: tangyuan2   File: TypeUtils.java   Source Code and License 5 votes vote down vote up
private static boolean checkField(Field field) {
	int modifiers = field.getModifiers();
	if (Modifier.isFinal(modifiers)) {
		return true;
	}
	if (Modifier.isTransient(modifiers)) {
		return true;
	}
	if (Modifier.isStatic(modifiers)) {
		return true;
	}
	return false;
}
 
Example 53
Project: OpenDA   File: ApplicationRunner.java   Source Code and License 5 votes vote down vote up
private static Constructor getWorkingDirAndConfigStringConstructor(Class implementingClass) {
	Constructor constructor;
	try {
		final Class workingDirClass = File.class;
		constructor = implementingClass.getConstructor(workingDirClass, String.class);
		if (!Modifier.isPublic(constructor.getModifiers())) {
			throw new RuntimeException("Constructor \"" + constructor.toString() + "\" must be public");
		}
	} catch (NoSuchMethodException e) {
		throw new RuntimeException("Constructor \"" + implementingClass + "(File workingDir, String configFile)\" not found");
	}
	return constructor;
}
 
Example 54
Project: lams   File: ClassUtils.java   Source Code and License 5 votes vote down vote up
/**
 * <p>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>
 * </p>
 *
 * @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 candidateClasses = new ArrayList();
    candidateClasses.addAll(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Iterator it = candidateClasses.iterator(); it.hasNext(); ) {
        Class candidateClass = (Class) it.next();
        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));
}
 
Example 55
Project: manifold   File: JavascriptProgram.java   Source Code and License 5 votes vote down vote up
static SrcClass genProgram(String fqn, ProgramNode programNode) {
  SrcClass clazz = new SrcClass(fqn, SrcClass.Kind.Class).superClass(JavascriptProgram.class)
    .imports(SourcePosition.class);

  clazz.addField(new SrcField("ENGINE", ScriptEngine.class)
    .modifiers(Modifier.STATIC)
    .initializer(new SrcRawExpression(("init(\"" + fqn + "\")"))));

  clazz.addConstructor(new SrcConstructor().modifiers(Modifier.PRIVATE).body(new SrcStatementBlock()));

  for (FunctionNode node : programNode.getChildren(FunctionNode.class)) {
    AbstractSrcMethod<SrcMethod> srcMethod = new SrcMethod()
      .name(node.getName())
      .modifiers(Modifier.STATIC | Modifier.PUBLIC)
      .returns(node.getReturnType());

    // params
    ParameterNode firstChild = node.getFirstChild(ParameterNode.class);
    for (SrcParameter srcParameter : firstChild.toParamList()) {
      srcMethod.addParam(srcParameter);
    }

    //impl
    srcMethod.body(new SrcStatementBlock()
      .addStatement(
        new SrcRawStatement()
          .rawText("return invoke(ENGINE, \"" + node.getName() + "\"" + generateArgList(firstChild.toParamList()) + ");")));
    clazz.addMethod(srcMethod);

  }
  return clazz;
}
 
Example 56
Project: lams   File: CompareToBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * <p>Appends to <code>builder</code> the comparison of <code>lhs</code>
 * to <code>rhs</code> using the fields defined in <code>clazz</code>.</p>
 * 
 * @param lhs  left-hand object
 * @param rhs  right-hand object
 * @param clazz  <code>Class</code> that defines fields to be compared
 * @param builder  <code>CompareToBuilder</code> to append to
 * @param useTransients  whether to compare transient fields
 * @param excludeFields  fields to exclude
 */
private static void reflectionAppend(
    Object lhs,
    Object rhs,
    Class clazz,
    CompareToBuilder builder,
    boolean useTransients,
    String[] excludeFields) {
    
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
        Field f = fields[i];
        if (!ArrayUtils.contains(excludeFields, f.getName())
            && (f.getName().indexOf('$') == -1)
            && (useTransients || !Modifier.isTransient(f.getModifiers()))
            && (!Modifier.isStatic(f.getModifiers()))) {
            try {
                builder.append(f.get(lhs), f.get(rhs));
            } catch (IllegalAccessException e) {
                // This can't happen. Would get a Security exception instead.
                // Throw a runtime exception in case the impossible happens.
                throw new InternalError("Unexpected IllegalAccessException");
            }
        }
    }
}
 
Example 57
Project: lams   File: ConstructorResolver.java   Source Code and License 5 votes vote down vote up
/**
 * Resolve the factory method in the specified bean definition, if possible.
 * {@link RootBeanDefinition#getResolvedFactoryMethod()} can be checked for the result.
 * @param mbd the bean definition to check
 */
public void resolveFactoryMethodIfPossible(RootBeanDefinition mbd) {
	Class<?> factoryClass;
	boolean isStatic;
	if (mbd.getFactoryBeanName() != null) {
		factoryClass = this.beanFactory.getType(mbd.getFactoryBeanName());
		isStatic = false;
	}
	else {
		factoryClass = mbd.getBeanClass();
		isStatic = true;
	}
	factoryClass = ClassUtils.getUserClass(factoryClass);

	Method[] candidates = getCandidateMethods(factoryClass, mbd);
	Method uniqueCandidate = null;
	for (Method candidate : candidates) {
		if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
			if (uniqueCandidate == null) {
				uniqueCandidate = candidate;
			}
			else if (!Arrays.equals(uniqueCandidate.getParameterTypes(), candidate.getParameterTypes())) {
				uniqueCandidate = null;
				break;
			}
		}
	}
	synchronized (mbd.constructorArgumentLock) {
		mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
	}
}
 
Example 58
Project: OpenJSharp   File: ReflectionFactory.java   Source Code and License 5 votes vote down vote up
private static LangReflectAccess langReflectAccess() {
    if (langReflectAccess == null) {
        // Call a static method to get class java.lang.reflect.Modifier
        // initialized. Its static initializer will cause
        // setLangReflectAccess() to be called from the context of the
        // java.lang.reflect package.
        Modifier.isPublic(Modifier.PUBLIC);
    }
    return langReflectAccess;
}
 
Example 59
Project: FridaAndroidTracer   File: FridaAndroidTracer.java   Source Code and License 5 votes vote down vote up
private static String hookClass(Class clazz, Set<String> skipMethods, boolean includePrivate,
        int indents) {
    StringWriter writer = new StringWriter();
    PrintWriter printer = new PrintWriter(writer);

    printIndents(printer, indents);
    printer.println("////////// auto-gen hook script for class: " + clazz.getName());

    printIndents(printer, indents);
    printer.println(String.format("var %s = Java.use(\"%s\");",
            clazz.getSimpleName(), clazz.getName()));

    printer.println();

    for (Constructor constructor : clazz.getConstructors()) {
        hookConstructor(printer, clazz, constructor, 1);
    }

    for (Method method : getMethods(clazz)) {
        if (skipMethods.contains(method.getName())) {
            continue;
        }

        if (Modifier.isPrivate(method.getModifiers()) && !includePrivate) {
            continue;
        }

        hookMethod(printer, clazz, method, 1);
    }

    printer.println();
    printer.close();

    return writer.toString();
}
 
Example 60
Project: openjdk-jdk10   File: UnsafeFieldAccessorImpl.java   Source Code and License 5 votes vote down vote up
UnsafeFieldAccessorImpl(Field field) {
    this.field = field;
    if (Modifier.isStatic(field.getModifiers()))
        fieldOffset = unsafe.staticFieldOffset(field);
    else
        fieldOffset = unsafe.objectFieldOffset(field);
    isFinal = Modifier.isFinal(field.getModifiers());
}