Java Code Examples for java.lang.reflect.Modifier#isPrivate()

The following examples show how to use java.lang.reflect.Modifier#isPrivate() . 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: ObjectStreamClass.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
protected ObjectStreamField[] computeValue(Class<?> type) {
    try {
        Field pf = type.getDeclaredField("serialPersistentFields");
        int mods = pf.getModifiers();
        if (Modifier.isPrivate(mods) && Modifier.isStatic(mods) &&
                Modifier.isFinal(mods)) {
            pf.setAccessible(true);
            java.io.ObjectStreamField[] fields =
                (java.io.ObjectStreamField[])pf.get(type);
            return translateFields(fields);
        }
    } catch (NoSuchFieldException | IllegalAccessException |
            IllegalArgumentException | ClassCastException e) {
    }
    return null;
}
 
Example 2
Source File: ReflectionFactory.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private final MethodHandle findReadWriteObjectForSerialization(Class<?> cl,
                                                               String methodName,
                                                               Class<?> streamClass) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    try {
        Method meth = cl.getDeclaredMethod(methodName, streamClass);
        int mods = meth.getModifiers();
        if (meth.getReturnType() != Void.TYPE ||
                Modifier.isStatic(mods) ||
                !Modifier.isPrivate(mods)) {
            return null;
        }
        meth.setAccessible(true);
        return MethodHandles.lookup().unreflect(meth);
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (IllegalAccessException ex1) {
        throw new InternalError("Error", ex1);
    }
}
 
Example 3
Source File: Indify.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
boolean findPatternMethods() {
    boolean found = false;
    for (char mark : "THI".toCharArray()) {
        for (Method m : cf.methods) {
            if (!Modifier.isPrivate(m.access))  continue;
            if (!Modifier.isStatic(m.access))  continue;
            if (nameAndTypeMark(m.name, m.type) == mark) {
                Constant con = scanPattern(m, mark);
                if (con == null)  continue;
                constants.put(m, con);
                found = true;
            }
        }
    }
    return found;
}
 
Example 4
Source File: ObjectStreamClassUtil_1_3.java    From openjdk-jdk8u with GNU General Public License v2.0 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 5
Source File: CheckUtilityClass.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that a utility class is well-formed; e.g., that it is
 * final, with a single private constructor and no non-static
 * methods
 * @param utilityClass The class to check
 */
public static void assertUtilityClassWellDefined(final Class<?> utilityClass)
    throws NoSuchMethodException, InvocationTargetException,
    InstantiationException, IllegalAccessException {
  assertTrue("Utility class must be final",
      Modifier.isFinal(utilityClass.getModifiers()));
  assertEquals("Utility class can only have one constructor", 1,
      utilityClass.getDeclaredConstructors().length);
  final Constructor<?> constructor = utilityClass.getDeclaredConstructor();
  if (!Modifier.isPrivate(constructor.getModifiers())) {
    fail("Utility class constructor must be private");
  }
  constructor.setAccessible(true);
  constructor.newInstance();
  constructor.setAccessible(false);
  for (final Method method : utilityClass.getMethods()) {
    if (!Modifier.isStatic(method.getModifiers())
        && method.getDeclaringClass().equals(utilityClass)) {
      fail("Utility class can only have static methods; found non-static method:" + method);
    }
  }
}
 
Example 6
Source File: Indify.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
boolean findPatternMethods() {
    boolean found = false;
    for (char mark : "THI".toCharArray()) {
        for (Method m : cf.methods) {
            if (!Modifier.isPrivate(m.access))  continue;
            if (!Modifier.isStatic(m.access))  continue;
            if (nameAndTypeMark(m.name, m.type) == mark) {
                Constant con = scanPattern(m, mark);
                if (con == null)  continue;
                constants.put(m, con);
                found = true;
            }
        }
    }
    return found;
}
 
Example 7
Source File: JsonViewSerializer.java    From json-view with GNU General Public License v3.0 6 votes vote down vote up
private Predicate<Field> fieldVisibilityAllowed(Class cls) {
  JsonAutoDetect autoDetect = getAnnotation(cls, JsonAutoDetect.class);

  if(autoDetect == null) {
    return f -> false;
  } else {
    switch(autoDetect.fieldVisibility()) {
      case ANY:
        return f -> true;
      case PUBLIC_ONLY:
        return f -> Modifier.isPublic(f.getModifiers());
      case PROTECTED_AND_PUBLIC:
        return f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers());
      case NON_PRIVATE:
        return f -> !Modifier.isPrivate(f.getModifiers());
      case DEFAULT:
      case NONE:
        return f -> false;
      default:
        throw new RuntimeException("No support for field visibility " + autoDetect.fieldVisibility());
    }
  }
}
 
Example 8
Source File: ReflectionFactory.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private final MethodHandle findReadWriteObjectForSerialization(Class<?> cl,
                                                               String methodName,
                                                               Class<?> streamClass) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    try {
        Method meth = cl.getDeclaredMethod(methodName, streamClass);
        int mods = meth.getModifiers();
        if (meth.getReturnType() != Void.TYPE ||
                Modifier.isStatic(mods) ||
                !Modifier.isPrivate(mods)) {
            return null;
        }
        meth.setAccessible(true);
        return MethodHandles.lookup().unreflect(meth);
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (IllegalAccessException ex1) {
        throw new InternalError("Error", ex1);
    }
}
 
Example 9
Source File: DependencyInjectingInstantiator.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static boolean isPublicOrPackageScoped(Class<?> type, Constructor<?> constructor) {
    if (isPackagePrivate(type.getModifiers())) {
        return !Modifier.isPrivate(constructor.getModifiers()) && !Modifier.isProtected(constructor.getModifiers());
    } else {
        return Modifier.isPublic(constructor.getModifiers());
    }
}
 
Example 10
Source File: SimpleConfig.java    From Jupiter with GNU General Public License v3.0 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 11
Source File: CreatorOptimizer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public ValueInstantiator createOptimized()
{
    /* [Issue#11]: Need to avoid optimizing if we use delegate- or
     *  property-based creators.
     */
    if (_originalInstantiator.canCreateFromObjectWith()
            || _originalInstantiator.canCreateUsingDelegate()) {
        return null;
    }
    
    // for now, only consider need to handle default creator
    AnnotatedWithParams defaultCreator = _originalInstantiator.getDefaultCreator();
    if (defaultCreator != null) {
        AnnotatedElement elem = defaultCreator.getAnnotated();
        if (elem instanceof Constructor<?>) {
            // First things first: as per [Issue#34], can NOT access private ctors or methods
            Constructor<?> ctor = (Constructor<?>) elem;
            if (!Modifier.isPrivate(ctor.getModifiers())) {
                return createSubclass(ctor, null).with(_originalInstantiator);
            }
        } else if (elem instanceof Method) {
            Method m = (Method) elem;
            int mods = m.getModifiers();
            // and as above, can't access private ones
            if (Modifier.isStatic(mods) && !Modifier.isPrivate(mods)) {
                return createSubclass(null, m).with(_originalInstantiator);
            }
        }
    }
    return null;
}
 
Example 12
Source File: ClassGenerator.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static String modifier(int mod)
{
	if( Modifier.isPublic(mod) ) return "public";
	if( Modifier.isProtected(mod) ) return "protected";
	if( Modifier.isPrivate(mod) ) return "private";
	return "";
}
 
Example 13
Source File: ClassUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether the given method is overridable in the given target class.
 * @param method the method to check
 * @param targetClass the target class to check against
 */
private static boolean isOverridable(Method method, Class<?> targetClass) {
	if (Modifier.isPrivate(method.getModifiers())) {
		return false;
	}
	if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
		return true;
	}
	return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass));
}
 
Example 14
Source File: Utils.java    From apkfile with Apache License 2.0 5 votes vote down vote up
public static void updateAccessorCounts(TObjectIntMap<String> counts, int[] accessFlags) {
    for (int accessFlag : accessFlags) {
        if (Modifier.isPublic(accessFlag)) {
            counts.adjustOrPutValue("public", 1, 1);
        }
        if (Modifier.isProtected(accessFlag)) {
            counts.adjustOrPutValue("protected", 1, 1);
        }
        if (Modifier.isPrivate(accessFlag)) {
            counts.adjustOrPutValue("private", 1, 1);
        }
        if (Modifier.isFinal(accessFlag)) {
            counts.adjustOrPutValue("final", 1, 1);
        }
        if (Modifier.isInterface(accessFlag)) {
            counts.adjustOrPutValue("interface", 1, 1);
        }
        if (Modifier.isNative(accessFlag)) {
            counts.adjustOrPutValue("native", 1, 1);
        }
        if (Modifier.isStatic(accessFlag)) {
            counts.adjustOrPutValue("static", 1, 1);
        }
        if (Modifier.isStrict(accessFlag)) {
            counts.adjustOrPutValue("strict", 1, 1);
        }
        if (Modifier.isSynchronized(accessFlag)) {
            counts.adjustOrPutValue("synchronized", 1, 1);
        }
        if (Modifier.isTransient(accessFlag)) {
            counts.adjustOrPutValue("transient", 1, 1);
        }
        if (Modifier.isVolatile(accessFlag)) {
            counts.adjustOrPutValue("volatile", 1, 1);
        }
        if (Modifier.isAbstract(accessFlag)) {
            counts.adjustOrPutValue("abstract", 1, 1);
        }
    }
}
 
Example 15
Source File: ScopedProxyFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (!(beanFactory instanceof ConfigurableBeanFactory)) {
		throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
	}
	ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;

	this.scopedTargetSource.setBeanFactory(beanFactory);

	ProxyFactory pf = new ProxyFactory();
	pf.copyFrom(this);
	pf.setTargetSource(this.scopedTargetSource);

	Class<?> beanType = beanFactory.getType(this.targetBeanName);
	if (beanType == null) {
		throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
				"': Target type could not be determined at the time of proxy creation.");
	}
	if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
		pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
	}

	// Add an introduction that implements only the methods on ScopedObject.
	ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
	pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));

	// Add the AopInfrastructureBean marker to indicate that the scoped proxy
	// itself is not subject to auto-proxying! Only its target bean is.
	pf.addInterface(AopInfrastructureBean.class);

	this.proxy = pf.getProxy(cbf.getBeanClassLoader());
}
 
Example 16
Source File: JConstructorWrapper.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns true for a private method
 */
public boolean isPrivate()
{
  return Modifier.isPrivate(_method.getModifiers());
}
 
Example 17
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new injection point for the injectable constructor of {@code type}.
 *
 * @param type a concrete type with exactly one constructor annotated {@literal @}{@link Inject},
 *             or a no-arguments constructor that is not private.
 * @throws ConfigurationException if there is no injectable constructor, more than one injectable
 *                                constructor, or if parameters of the injectable constructor are malformed, such as a
 *                                parameter with multiple binding annotations.
 */
public static InjectionPoint forConstructorOf(TypeLiteral<?> type) {
    Class<?> rawType = getRawType(type.getType());
    Errors errors = new Errors(rawType);

    Constructor<?> injectableConstructor = null;
    for (Constructor<?> constructor : rawType.getDeclaredConstructors()) {
        Inject inject = constructor.getAnnotation(Inject.class);
        if (inject != null) {
            if (inject.optional()) {
                errors.optionalConstructor(constructor);
            }

            if (injectableConstructor != null) {
                errors.tooManyConstructors(rawType);
            }

            injectableConstructor = constructor;
            checkForMisplacedBindingAnnotations(injectableConstructor, errors);
        }
    }

    errors.throwConfigurationExceptionIfErrorsExist();

    if (injectableConstructor != null) {
        return new InjectionPoint(type, injectableConstructor);
    }

    // If no annotated constructor is found, look for a no-arg constructor instead.
    try {
        Constructor<?> noArgConstructor = rawType.getDeclaredConstructor();

        // Disallow private constructors on non-private classes (unless they have @Inject)
        if (Modifier.isPrivate(noArgConstructor.getModifiers())
                && !Modifier.isPrivate(rawType.getModifiers())) {
            errors.missingConstructor(rawType);
            throw new ConfigurationException(errors.getMessages());
        }

        checkForMisplacedBindingAnnotations(noArgConstructor, errors);
        return new InjectionPoint(type, noArgConstructor);
    } catch (NoSuchMethodException e) {
        errors.missingConstructor(rawType);
        throw new ConfigurationException(errors.getMessages());
    }
}
 
Example 18
Source File: DependencyInjectingInstantiator.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static boolean isPackagePrivate(int modifiers) {
    return !Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers) && !Modifier.isPublic(modifiers);
}
 
Example 19
Source File: Reflect.java    From beanshell with Apache License 2.0 4 votes vote down vote up
static boolean isPrivate(Member member) {
    return Modifier.isPrivate(member.getModifiers());
}
 
Example 20
Source File: ReflectiveModuleParser.java    From dagger-reflect with Apache License 2.0 4 votes vote down vote up
private static void ensureNotPrivate(Method method) {
  if (Modifier.isPrivate(method.getModifiers())) {
    throw new IllegalArgumentException("Provides methods may not be private: " + method);
  }
}