java.lang.reflect.Modifier Java Examples

The following examples show how to use java.lang.reflect.Modifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpannerStructReadMethodCoverageTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void allKnownMappingTypesTest() throws NoSuchFieldException {
	for (Method method : Struct.class.getMethods()) {
		String methodName = method.getName();
		// ignoring private methods, ones not named like a getter. Getters must also
		// only take the column index or name
		if (!Modifier.isPublic(method.getModifiers()) || !methodName.startsWith("get")
				|| method.getParameterCount() != 1
				|| DISREGARDED_METHOD_NAMES.contains(methodName)) {
			continue;
		}
		Class returnType = ConversionUtils.boxIfNeeded(method.getReturnType());
		if (ConversionUtils.isIterableNonByteArrayType(returnType)) {
			Class innerReturnType = (Class) ((ParameterizedType) method
					.getGenericReturnType()).getActualTypeArguments()[0];
			assertThat(StructAccessor.readIterableMapping.keySet()).contains(innerReturnType);
		}
		else {
			assertThat(StructAccessor.singleItemReadMethodMapping.keySet()).contains(returnType);
		}
	}
}
 
Example #2
Source File: BeanUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
public static boolean setFieldValue(Object obj, Field field, Object value){ 
	if(null == obj || null == field){ 
		return false; 
	} 
	if(Modifier.isStatic(field.getModifiers())){ 
		return false; 
	} 
	try{
		if(field.isAccessible()){
			//可访问属性
			field.set(obj, value);
		}else{
			//不可访问属性
			field.setAccessible(true);
			field.set(obj, value);
			field.setAccessible(false);
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
	return true; 
}
 
Example #3
Source File: GeciReflectionTools.java    From javageci with Apache License 2.0 6 votes vote down vote up
/**
 * Convert an int containing modifiers bits to string containing the Java names of the modifiers space separated.
 *
 * @param modifiers to be converted to string
 * @return the space separated modifiers or empty string in case there is no modifier bit set in {@code modifiers}
 */
public static String unmask(int modifiers) {
    final StringBuilder s = new StringBuilder();
    final BiConsumer<Predicate<Integer>, String> check = (Predicate<Integer> predicate, String text) -> {
        if (predicate.test(modifiers)) {
            s.append(text);
        }
    };
    check.accept(Modifier::isPrivate, "private ");
    check.accept(Modifier::isProtected, "protected ");
    check.accept(Modifier::isPublic, "public ");
    check.accept(Modifier::isFinal, "final ");
    check.accept(Modifier::isStatic, "static ");
    check.accept(Modifier::isSynchronized, "synchronized ");
    check.accept(Modifier::isVolatile, "volatile ");
    check.accept(Modifier::isStrict, "strictfp ");
    check.accept(Modifier::isAbstract, "abstract ");
    check.accept(Modifier::isTransient, "transient ");
    return s.toString().trim();
}
 
Example #4
Source File: Selector.java    From javageci with Apache License 2.0 6 votes vote down vote up
/**
 * -
 * <p>
 * ### Class and method checking selectors
 *
 * <p> These conditions work on classes and on methods. Applying
 * them on a field will throw exception.
 */
private void methodAndClassOnlySelectors() {
    /**
     * -
     *
     * * `abstract` is `true` if the type of method is abstract.
     *
     */
    selector("abstract", m -> only(m, Class.class, Method.class) && Modifier.isAbstract(getModifiers(m)));
    /**
     * -
     *
     * * `implements` is `true` if the class implements at least one
     * interface. When applied to a method it is `true` if the
     * method implements a method of the same name and argument
     * types in one of the interfaces the class directly or
     * indirectly implements. In other words it means that there is
     * an interface that declares this method and this method is an
     * implementation (not abstract).
     *
     */
    selector("implements", m -> only(m, Class.class, Method.class) && methodOrClassImplements(m));
}
 
Example #5
Source File: ObjectStreamClass.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns subclass-accessible no-arg constructor of first non-serializable
 * superclass, or null if none found.  Access checks are disabled on the
 * returned constructor (if any).
 */
private static Constructor<?> getSerializableConstructor(Class<?> cl) {
    Class<?> initCl = cl;
    while (Serializable.class.isAssignableFrom(initCl)) {
        if ((initCl = initCl.getSuperclass()) == null) {
            return null;
        }
    }
    try {
        Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
        int mods = cons.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
            ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
             !packageEquals(cl, initCl)))
        {
            return null;
        }
        cons = reflFactory.newConstructorForSerialization(cl, cons);
        cons.setAccessible(true);
        return cons;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example #6
Source File: NewInstanceMutationOperator.java    From pitest-descartes with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns a value indicating whether the operator can transform the given method.
 */
@Override
public boolean canMutate(Method method) {
    try {
        Class<?> returnClass = getAppropriateReturnClass(method);

        if(returnClass.equals(String.class)
                || !belongsToJavaPackages(returnClass)
                || Modifier.isAbstract(returnClass.getModifiers())) {
            return false;
        }
        for (Constructor<?> publicConstructor : returnClass.getConstructors()) {
            if (publicConstructor.getParameters().length == 0) {
                return true;
            }
        }
        return false;
    }
    catch (ClassNotFoundException e) {
        return false;
    }
}
 
Example #7
Source File: JMX.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * <p>Test whether an interface is an MXBean interface.
 * An interface is an MXBean interface if it is public,
 * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
 * or if it does not have an {@code @MXBean} annotation
 * and its name ends with "{@code MXBean}".</p>
 *
 * @param interfaceClass The candidate interface.
 *
 * @return true if {@code interfaceClass} is a
 * {@link javax.management.MXBean compliant MXBean interface}
 *
 * @throws NullPointerException if {@code interfaceClass} is null.
 */
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
    // We don't bother excluding the case where the name is
    // exactly the string "MXBean" since that would mean there
    // was no package name, which is pretty unlikely in practice.
}
 
Example #8
Source File: ScalarFunctionImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link org.apache.calcite.schema.ScalarFunction} for each method in
 * a given class.
 */
public static ImmutableMultimap<String, ScalarFunction> createAll(
    Class<?> clazz) {
  final ImmutableMultimap.Builder<String, ScalarFunction> builder =
      ImmutableMultimap.builder();
  for (Method method : clazz.getMethods()) {
    if (method.getDeclaringClass() == Object.class) {
      continue;
    }
    if (!Modifier.isStatic(method.getModifiers())
        && !classHasPublicZeroArgsConstructor(clazz)) {
      continue;
    }
    final ScalarFunction function = create(method);
    builder.put(method.getName(), function);
  }
  return builder.build();
}
 
Example #9
Source File: SwingTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void start() throws Throwable {
    do {
        if ((this.method != null) && Modifier.isStatic(this.method.getModifiers())) {
            run(); // invoke static method on the current thread
        }
        else {
            SwingUtilities.invokeLater(this); // invoke on the event dispatch thread
        }
        Toolkit tk = Toolkit.getDefaultToolkit();
        if (tk instanceof SunToolkit) {
            SunToolkit stk = (SunToolkit) tk;
            stk.realSync(); // wait until done
        }
    }
    while (this.frame != null);
    if (this.error != null) {
        throw this.error;
    }
}
 
Example #10
Source File: JMX.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Test whether an interface is an MXBean interface.
 * An interface is an MXBean interface if it is public,
 * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
 * or if it does not have an {@code @MXBean} annotation
 * and its name ends with "{@code MXBean}".</p>
 *
 * @param interfaceClass The candidate interface.
 *
 * @return true if {@code interfaceClass} is a
 * {@link javax.management.MXBean compliant MXBean interface}
 *
 * @throws NullPointerException if {@code interfaceClass} is null.
 */
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
    // We don't bother excluding the case where the name is
    // exactly the string "MXBean" since that would mean there
    // was no package name, which is pretty unlikely in practice.
}
 
Example #11
Source File: Reflector2.java    From clj-graal-docs with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isAccessibleMatch(Method lhs, Method rhs, Object target) {
        if(!lhs.getName().equals(rhs.getName())
                        || !Modifier.isPublic(lhs.getDeclaringClass().getModifiers())
                        || !canAccess(lhs, target))
        {
                return false;
        }

        Class[] types1 = lhs.getParameterTypes();
        Class[] types2 = rhs.getParameterTypes();
        if(types1.length != types2.length)
                return false;

        boolean match = true;
        for (int i=0; i<types1.length; ++i)
        {
                if(!types1[i].isAssignableFrom(types2[i]))
                {
                        match = false;
                        break;
                }
        }
        return match;
}
 
Example #12
Source File: ExcelUtils.java    From poi-excel-utils with Apache License 2.0 6 votes vote down vote up
private static void readConfigParamVerify(ExcelReadSheetProcessor<?> sheetProcessor,
                                          Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> fieldMapping) {
    Class<?> clazz = sheetProcessor.getTargetClass();

    for (Entry<Integer, Map<String, ExcelReadFieldMappingAttribute>> indexFieldMapping : fieldMapping.entrySet()) {
        for (Map.Entry<String, ExcelReadFieldMappingAttribute> filedMapping : indexFieldMapping.getValue().entrySet()) {
            String fieldName = filedMapping.getKey();
            if (fieldName != null) {
                PropertyDescriptor pd = getPropertyDescriptor(clazz, fieldName);
                if (pd == null || pd.getWriteMethod() == null) {
                    throw new IllegalArgumentException("In fieldMapping config {colIndex:"
                                                       + indexFieldMapping.getKey() + "["
                                                       + convertColIntIndexToCharIndex(indexFieldMapping.getKey())
                                                       + "]<->fieldName:" + filedMapping.getKey() + "}, "
                                                       + " class " + clazz.getName() + " can't find field '"
                                                       + filedMapping.getKey() + "' and can not also find "
                                                       + filedMapping.getKey() + "'s writter method.");
                }
                if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                    pd.getWriteMethod().setAccessible(true);
                }
            }
        }
    }
}
 
Example #13
Source File: LuaMapping.java    From Cubes with MIT 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 #14
Source File: InvokerBytecodeGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 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 #15
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private void resetClassFields(final Class<?> aClass) {
  if (aClass == null) return;

  final Field[] fields = aClass.getDeclaredFields();
  for (Field field : fields) {
    final int modifiers = field.getModifiers();
    if ((modifiers & Modifier.FINAL) == 0
        && (modifiers & Modifier.STATIC) == 0
        && !field.getType().isPrimitive()) {
      field.setAccessible(true);
      try {
        field.set(this, null);
      }
      catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }

  if (aClass == ExternalSystemTestCase.class) return;
  resetClassFields(aClass.getSuperclass());
}
 
Example #16
Source File: MVELConstraintBuilder.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public boolean areEqualityCompatible(Class<?> c1, Class<?> c2) {
    if (c1 == NullType.class || c2 == NullType.class) {
        return true;
    }
    if (c1 == String.class || c2 == String.class) {
        return true;
    }
    Class<?> boxed1 = convertFromPrimitiveType(c1);
    Class<?> boxed2 = convertFromPrimitiveType(c2);
    if (boxed1.isAssignableFrom(boxed2) || boxed2.isAssignableFrom(boxed1)) {
        return true;
    }
    if (Number.class.isAssignableFrom(boxed1) && Number.class.isAssignableFrom(boxed2)) {
        return true;
    }
    return !Modifier.isFinal(c1.getModifiers()) && !Modifier.isFinal(c2.getModifiers());
}
 
Example #17
Source File: ReflectUtil.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Does a conservative approximation of member access check. Use this if
 * you don't have an actual 'userland' caller Class/ClassLoader available.
 * This might be more restrictive than a precise member access check where
 * you have a caller, but should never allow a member access that is
 * forbidden.
 *
 * @param m the {@code Member} about to be accessed
 */
public static void conservativeCheckMemberAccess(Member m) throws SecurityException{
    final SecurityManager sm = System.getSecurityManager();
    if (sm == null)
        return;

    // Check for package access on the declaring class.
    //
    // In addition, unless the member and the declaring class are both
    // public check for access declared member permissions.
    //
    // This is done regardless of ClassLoader relations between the {@code
    // Member m} and any potential caller.

    final Class<?> declaringClass = m.getDeclaringClass();

    checkPackageAccess(declaringClass);

    if (Modifier.isPublic(m.getModifiers()) &&
            Modifier.isPublic(declaringClass.getModifiers()))
        return;

    // Check for declared member access.
    sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
}
 
Example #18
Source File: JsonUtils.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
/**
 * JSON 转 ArrayList
 *
 * @author [email protected]
 * @date 2018年10月27日下午4:43:25
 */
public static ArrayList<?> jsonArrayToArrayList(String jsonArray, Class<?> clazz) {

    Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();
    ArrayList<?> list = null;
    try {

        list = (ArrayList<?>) gson.fromJson(jsonArray, clazz);
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    }
    return list;
}
 
Example #19
Source File: AnalyzedMethod.java    From glowroot with Apache License 2.0 6 votes vote down vote up
boolean isOverriddenBy(String methodName, List<Type> parameterTypes) {
    if (Modifier.isStatic(modifiers())) {
        return false;
    }
    if (Modifier.isPrivate(modifiers())) {
        return false;
    }
    if (!methodName.equals(name())) {
        return false;
    }
    if (parameterTypes.size() != parameterTypes().size()) {
        return false;
    }
    for (int i = 0; i < parameterTypes.size(); i++) {
        if (!parameterTypes.get(i).getClassName().equals(parameterTypes().get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #20
Source File: ExposureSupport.java    From Tangram-Android with MIT License 6 votes vote down vote up
private void findExposureMethods(Method[] methods) {
    for (Method method : methods) {
        String methodName = method.getName();
        if (isValidExposureMethodName(methodName)) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 3) {
                    Class<?> viewType = parameterTypes[0];
                    Class<?> cellType = parameterTypes[1];
                    Class<?> clickIntType = parameterTypes[2];
                    if (View.class.isAssignableFrom(viewType)
                            && BaseCell.class.isAssignableFrom(cellType)
                            && (clickIntType.equals(int.class) || clickIntType
                            .equals(Integer.class))) {
                        mOnExposureMethods.put(viewType, new OnTraceMethod(3, method));
                    }
                }
            }
        }
    }
}
 
Example #21
Source File: Accessor.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #22
Source File: MixAll.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static void printObjectProperties(final Logger logger, final Object object,
    final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }
                } catch (IllegalAccessException e) {
                    log.error("Failed to obtain object properties", e);
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (logger != null) {
                    logger.info(name + "=" + value);
                } else {
                }
            }
        }
    }
}
 
Example #23
Source File: Reflector.java    From clj-graal-docs with Eclipse Public License 1.0 5 votes vote down vote up
static public Field getField(Class c, String name, boolean getStatics){
    Field[] allfields = c.getFields();
    for(int i = 0; i < allfields.length; i++)
        {
            if(name.equals(allfields[i].getName())
               && Modifier.isStatic(allfields[i].getModifiers()) == getStatics)
                return allfields[i];
        }
    return null;
}
 
Example #24
Source File: UnsafeAllocator.java    From sagetv with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the class can be instantiated by unsafe allocator. If the instance has interface or abstract modifiers
 * throw an {@link java.lang.UnsupportedOperationException}
 * @param c instance of the class to be checked
 */
private static void assertInstantiable(Class<?> c) {
  int modifiers = c.getModifiers();
  if (Modifier.isInterface(modifiers)) {
    throw new UnsupportedOperationException("Interface can't be instantiated! Interface name: " + c.getName());
  }
  if (Modifier.isAbstract(modifiers)) {
    throw new UnsupportedOperationException("Abstract class can't be instantiated! Class name: " + c.getName());
  }
}
 
Example #25
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Use the Jandex index to find all jax-rs resource classes. This is done by searching for
 * all Class-level @Path annotations.
 * 
 * @param index IndexView
 * @return Collection of ClassInfo's
 */
private Collection<ClassInfo> getJaxRsResourceClasses(IndexView index) {
    return index.getAnnotations(JaxRsConstants.PATH)
            .stream()
            .map(AnnotationInstance::target)
            .filter(target -> target.kind() == AnnotationTarget.Kind.CLASS)
            .map(AnnotationTarget::asClass)
            .filter(classInfo -> !Modifier.isInterface(classInfo.flags()) ||
                    index.getAllKnownImplementors(classInfo.name()).stream()
                            .anyMatch(info -> !Modifier.isAbstract(info.flags())))
            .distinct() // CompositeIndex instances may return duplicates
            .collect(Collectors.toList());
}
 
Example #26
Source File: AbstractPlugin.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * Check given class modifiers. Plugin with resources plugin should not be private or abstract
 * or interface.
 */
private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {
    int modifiers = pluginClass.getModifiers();
    return !Modifier.isAbstract(modifiers) &&
            !Modifier.isInterface(modifiers) &&
            !Modifier.isPrivate(modifiers);
}
 
Example #27
Source File: ReflectUtils.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static boolean isBeanPropertyReadMethod(Method method) {
	return method != null
			&& Modifier.isPublic(method.getModifiers())
			&& !Modifier.isStatic(method.getModifiers())
			&& method.getReturnType() != void.class
			&& method.getDeclaringClass() != Object.class
			&& method.getParameterTypes().length == 0
			&& ((method.getName().startsWith("get") && method.getName()
					.length() > 3) || (method.getName().startsWith("is") && method
					.getName().length() > 2));
}
 
Example #28
Source File: NifiPropertiesWriterTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCanUpdateAllKeys() throws IllegalAccessException, IOException {
    String testValue = NifiPropertiesWriterTest.class.getCanonicalName();

    // Get all property keys from NiFiProperties and set them to testValue
    Set<String> propertyKeys = new HashSet<>();
    for (Field field : NiFiProperties.class.getDeclaredFields()) {
        int modifiers = field.getModifiers();
        if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && field.getType() == String.class) {
            if (!field.getName().toLowerCase().startsWith("default")) {
                String fieldName = (String) field.get(null);
                propertyKeys.add(fieldName);
                niFiPropertiesWriter.setPropertyValue(fieldName, testValue);
            }
        }
    }

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    niFiPropertiesWriter.writeNiFiProperties(outputStream);

    // Verify operation worked
    Properties properties = new Properties();
    properties.load(new ByteArrayInputStream(outputStream.toByteArray()));
    for (String propertyKey : propertyKeys) {
        assertEquals(testValue, properties.getProperty(propertyKey));
    }
}
 
Example #29
Source File: AtomicIntegerFieldUpdater.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
AtomicIntegerFieldUpdaterImpl(final Class<T> tclass,
                              final String fieldName,
                              final Class<?> caller) {
    final Field field;
    final int modifiers;
    try {
        field = AccessController.doPrivileged(
            new PrivilegedExceptionAction<Field>() {
                public Field run() throws NoSuchFieldException {
                    return tclass.getDeclaredField(fieldName);
                }
            });
        modifiers = field.getModifiers();
        sun.reflect.misc.ReflectUtil.ensureMemberAccess(
            caller, tclass, null, modifiers);
        ClassLoader cl = tclass.getClassLoader();
        ClassLoader ccl = caller.getClassLoader();
        if ((ccl != null) && (ccl != cl) &&
            ((cl == null) || !isAncestor(cl, ccl))) {
            sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
        }
    } catch (PrivilegedActionException pae) {
        throw new RuntimeException(pae.getException());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    if (field.getType() != int.class)
        throw new IllegalArgumentException("Must be integer type");

    if (!Modifier.isVolatile(modifiers))
        throw new IllegalArgumentException("Must be volatile type");

    this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
    this.tclass = tclass;
    this.offset = U.objectFieldOffset(field);
}
 
Example #30
Source File: Introspector.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Basic method for testing that a MBean of a given class can be
 * instantiated by the MBean server.<p>
 * This method checks that:
 * <ul><li>The given class is a concrete class.</li>
 *     <li>The given class exposes at least one public constructor.</li>
 * </ul>
 * If these conditions are not met, throws a NotCompliantMBeanException.
 * @param c The class of the MBean we want to create.
 * @exception NotCompliantMBeanException if the MBean class makes it
 *            impossible to instantiate the MBean from within the
 *            MBeanServer.
 *
 **/
public static void testCreation(Class<?> c)
    throws NotCompliantMBeanException {
    // Check if the class is a concrete class
    final int mods = c.getModifiers();
    if (Modifier.isAbstract(mods) || Modifier.isInterface(mods)) {
        throw new NotCompliantMBeanException("MBean class must be concrete");
    }

    // Check if the MBean has a public constructor
    final Constructor<?>[] consList = c.getConstructors();
    if (consList.length == 0) {
        throw new NotCompliantMBeanException("MBean class must have public constructor");
    }
}