Java Code Examples for java.lang.reflect.Modifier#PRIVATE

The following examples show how to use java.lang.reflect.Modifier#PRIVATE . 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 jdk8u_jdk with GNU General Public License v2.0 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 2
Source File: ObjectStreamClass.java    From hottub with GNU General Public License v2.0 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 3
Source File: SchedulerProviderLookup.java    From tascalate-async-await with BSD 2-Clause "Simplified" License 6 votes vote down vote up
final protected boolean isVisibleTo(Class<?> subClass, Member member) {
    Class<?> declaringClass = member.getDeclaringClass();
    if (!declaringClass.isAssignableFrom(subClass)) {
        return false;
    }
    int modifiers = member.getModifiers();
    if (0 != (modifiers & (Modifier.PUBLIC | Modifier.PROTECTED))) {
        return true;
    } else {
        if (0 != (modifiers & Modifier.PRIVATE)) {
            return subClass == declaringClass;
        } else {
            return subClass.getPackage().equals(declaringClass.getPackage());
        }
    }
    
}
 
Example 4
Source File: ReflectionFactory.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an accessible no-arg constructor for a class.
 * The no-arg constructor is found searching the class and its supertypes.
 *
 * @param cl the class to instantiate
 * @return a no-arg constructor for the class or {@code null} if
 *     the class or supertypes do not have a suitable no-arg constructor
 */
public final Constructor<?> newConstructorForSerialization(Class<?> cl) {
    Class<?> initCl = cl;
    while (Serializable.class.isAssignableFrom(initCl)) {
        if ((initCl = initCl.getSuperclass()) == null) {
            return null;
        }
    }
    Constructor<?> constructorToCall;
    try {
        constructorToCall = initCl.getDeclaredConstructor();
        int mods = constructorToCall.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
                ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
                        !packageEquals(cl, initCl))) {
            return null;
        }
    } catch (NoSuchMethodException ex) {
        return null;
    }
    return generateConstructor(cl, constructorToCall);
}
 
Example 5
Source File: ObjectStreamClass.java    From openjdk-8 with GNU General Public License v2.0 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
Source File: ObjectStreamClass.java    From openjdk-jdk8u with GNU General Public License v2.0 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 7
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(new Class<?>[0]);
        int mods = cons.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
            ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
             !packageEquals(cl, initCl)))
        {
            return null;
        }
        cons = bridge.newConstructorForSerialization(cl, cons);
        cons.setAccessible(true);
        return cons;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 8
Source File: ObjectStreamClass.java    From jdk8u-dev-jdk with GNU General Public License v2.0 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 9
Source File: ObjectStreamClass.java    From jdk8u60 with GNU General Public License v2.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(new Class<?>[0]);
        int mods = cons.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
            ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
             !packageEquals(cl, initCl)))
        {
            return null;
        }
        cons = bridge.newConstructorForSerialization(cl, cons);
        cons.setAccessible(true);
        return cons;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 10
Source File: PrivateLambdas.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

      // Check that all the lambda methods are private instance synthetic
      for (Class<?> k : new Class<?>[] { A.class, B.class, C.class }) {
         Method[] methods = k.getDeclaredMethods();
         int lambdaCount = 0;
         for(Method m : methods) {
            if (m.getName().startsWith("lambda$")) {
               ++lambdaCount;
               int mod = m.getModifiers();
               if ((mod & Modifier.PRIVATE) == 0) {
                  throw new Exception("Expected " + m + " to be private");
               }
               if (!m.isSynthetic()) {
                  throw new Exception("Expected " + m + " to be synthetic");
               }
               if ((mod & Modifier.STATIC) != 0) {
                  throw new Exception("Expected " + m + " to be instance method");
               }
            }
         }
         if (lambdaCount == 0) {
            throw new Exception("Expected at least one lambda method");
         }
      }

      /*
       * Unless the lambda methods are private, this will fail with:
       *  AbstractMethodError:
       *        Conflicting default methods: A.lambda$0 B.lambda$0 C.lambda$0
       */
      X x = new PrivateLambdas();
      if (!x.name().equals(" A B C")) {
         throw new Exception("Expected ' A B C' got: " + x.name());
      }
   }
 
Example 11
Source File: PrivateLambdas.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

      // Check that all the lambda methods are private instance synthetic
      for (Class<?> k : new Class<?>[] { A.class, B.class, C.class }) {
         Method[] methods = k.getDeclaredMethods();
         int lambdaCount = 0;
         for(Method m : methods) {
            if (m.getName().startsWith("lambda$")) {
               ++lambdaCount;
               int mod = m.getModifiers();
               if ((mod & Modifier.PRIVATE) == 0) {
                  throw new Exception("Expected " + m + " to be private");
               }
               if (!m.isSynthetic()) {
                  throw new Exception("Expected " + m + " to be synthetic");
               }
               if ((mod & Modifier.STATIC) != 0) {
                  throw new Exception("Expected " + m + " to be instance method");
               }
            }
         }
         if (lambdaCount == 0) {
            throw new Exception("Expected at least one lambda method");
         }
      }

      /*
       * Unless the lambda methods are private, this will fail with:
       *  AbstractMethodError:
       *        Conflicting default methods: A.lambda$0 B.lambda$0 C.lambda$0
       */
      X x = new PrivateLambdas();
      if (!x.name().equals(" A B C")) {
         throw new Exception("Expected ' A B C' got: " + x.name());
      }
   }
 
Example 12
Source File: FieldArrayTest.java    From reflection-no-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void mapsAnnotatedObjectArrayField() throws ClassNotFoundException {
    javaSourceCode("test.Foo", //
                   "package test;", //
                   "public class Foo {",//
                   "@Deprecated private String[] s;", //
                   "}" //
    );

    setTargetAnnotations(new String[] {"java.lang.Deprecated"});
    assertJavaSourceCompileWithoutError();

    final Set<Class> annotatedClasses = getProcessedClasses();
    assertThat(annotatedClasses.contains(Class.forNameSafe("test.Foo")), is(true));

    final Class aClass = Class.forName("test.Foo");
    assertThat(aClass.getFields().length, is(1));

    final Field aField = aClass.getFields()[0];
    final Field expected = new Field("s", Class.forName("java.lang.String[]"), aClass, Modifier.PRIVATE, null);
    assertThat(aField, is(expected));
    assertThat(aField.getType(), is((Class) Class.forName("java.lang.String[]")));
    assertThat(aField.getType().isArray(), is(true));
    assertThat(aField.getType().getComponentType(), is((Class) Class.forName("java.lang.String")));
    assertThat(aField.getModifiers(), is(Modifier.PRIVATE));

    final Annotation[] annotations = (Annotation[]) aField.getAnnotations();
    assertThat(annotations.length, is(1));

    final Class deprecatedAnnotationClass = Class.forName("java.lang.Deprecated");
    assertThat(annotations[0].rnrAnnotationType(), is(deprecatedAnnotationClass));
    assertThat(((Annotation) aField.getAnnotation(deprecatedAnnotationClass)).rnrAnnotationType(), is(deprecatedAnnotationClass));

}
 
Example 13
Source File: DexMaker.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Declares a method or constructor.
 *
 * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link
 *              Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC},
 *              {@link Modifier#FINAL} and {@link Modifier#SYNCHRONIZED}.
 *              <p><strong>Warning:</strong> the {@link Modifier#SYNCHRONIZED} flag
 *              is insufficient to generate a synchronized method. You must also use
 *              {@link Code#monitorEnter} and {@link Code#monitorExit} to acquire
 *              a monitor.
 */
public Code declare(MethodId<?, ?> method, int flags) {
    TypeDeclaration typeDeclaration = getTypeDeclaration(method.declaringType);
    if (typeDeclaration.methods.containsKey(method)) {
        throw new IllegalStateException("already declared: " + method);
    }

    int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED
            | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED |
            Modifier.ABSTRACT | Modifier.NATIVE;
    if ((flags & ~supportedFlags) != 0) {
        throw new IllegalArgumentException("Unexpected flag: "
                + Integer.toHexString(flags));
    }
    if ((flags & Modifier.ABSTRACT) != 0 && (flags & Modifier.NATIVE) != 0) {
        throw new IllegalArgumentException("Native method can't be abstract");
    }

    // replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag
    if ((flags & Modifier.SYNCHRONIZED) != 0) {
        flags = (flags & ~Modifier.SYNCHRONIZED) | AccessFlags.ACC_DECLARED_SYNCHRONIZED;
    }

    if (method.isConstructor() || method.isStaticInitializer()) {
        flags |= ACC_CONSTRUCTOR;
    }

    MethodDeclaration methodDeclaration = new MethodDeclaration(method, flags);
    typeDeclaration.methods.put(method, methodDeclaration);
    return methodDeclaration.code;
}
 
Example 14
Source File: ForInnerClass.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /* We are not testing for the ACC_SUPER bug, so strip we strip
     * synchorized. */

    int m = 0;

    m = Inner.class.getModifiers() & (~Modifier.SYNCHRONIZED);
    if (m != Modifier.PRIVATE)
        throw new Exception("Access bits for innerclass not from " +
                            "InnerClasses attribute");

    m = Protected.class.getModifiers() & (~Modifier.SYNCHRONIZED);
    if (m != Modifier.PROTECTED)
        throw new Exception("Protected inner class wronged modifiers");
}
 
Example 15
Source File: ObjectStreamClass.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns non-static, non-abstract method with given signature provided it
 * is defined by or accessible (via inheritance) by the given class, or
 * null if no match found.  Access checks are disabled on the returned
 * method (if any).
 *
 * Copied from the Merlin java.io.ObjectStreamClass.
 */
private static Method getInheritableMethod(Class<?> cl, String name,
                                           Class<?>[] argTypes,
                                           Class<?> returnType)
{
    Method meth = null;
    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            meth = defCl.getDeclaredMethod(name, argTypes);
            break;
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }

    if ((meth == null) || (meth.getReturnType() != returnType)) {
        return null;
    }
    int mods = meth.getModifiers();
    if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
        return null;
    } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
        return meth;
    } else if ((mods & Modifier.PRIVATE) != 0) {
        return (cl == defCl) ? meth : null;
    } else {
        return packageEquals(cl, defCl) ? meth : null;
    }
}
 
Example 16
Source File: JavaMethod.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String modifierToString(int mod) {
    if ((mod & Modifier.PUBLIC) != 0)    return "public";
    if ((mod & Modifier.PROTECTED) != 0) return "protected";
    if ((mod & Modifier.PRIVATE) != 0)   return "private";
    return "";
}
 
Example 17
Source File: PojoFieldImpl.java    From openpojo with Apache License 2.0 4 votes vote down vote up
public boolean isPackagePrivate() {
  int modifiers = field.getModifiers();
  return (Modifier.PRIVATE & modifiers
      | Modifier.PROTECTED & modifiers
      | Modifier.PUBLIC & modifiers) == 0;
}
 
Example 18
Source File: VOClassTest.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * A VO must only have getter and setter which have a corresponding field
 * (with some exception which are defined below).
 */
@Test
public void testVOMethods() throws Exception {
    Map<Class<?>, Set<String>> allowedMethodNames = new HashMap<Class<?>, Set<String>>();
    Set<String> methodNames;

    methodNames = new HashSet<String>();
    methodNames.add("isValueTypeBoolean");
    methodNames.add("isValueTypeInteger");
    methodNames.add("isValueTypeLong");
    methodNames.add("isValueTypeString");
    methodNames.add("isValueTypeDuration");
    methodNames.add("isValueTypeEnumeration");
    methodNames.add("isValueTypePWD");
    allowedMethodNames.put(VOParameterDefinition.class, methodNames);

    methodNames = new HashSet<String>();
    methodNames.add("getCurrency");
    methodNames.add("isChargeable");
    allowedMethodNames.put(VOPriceModel.class, methodNames);

    methodNames = new HashSet<String>();
    methodNames.add("getNameToDisplay");
    allowedMethodNames.put(VOService.class, methodNames);

    methodNames = new HashSet<String>();
    methodNames.add("addUserRole");
    methodNames.add("removeUserRole");
    allowedMethodNames.put(VOUser.class, methodNames);

    methodNames = new HashSet<String>();
    methodNames.add("hasAdminRole");
    allowedMethodNames.put(VOUserDetails.class, methodNames);

    methodNames = new HashSet<String>();
    methodNames.add("setProperty");
    methodNames.add("getProperty");
    methodNames.add("asProperties");
    methodNames.add("get");
    allowedMethodNames.put(LdapProperties.class, methodNames);

    StringBuffer errors = new StringBuffer();
    List<Class<?>> classes = PackageClassReader.getClasses(BaseVO.class,
            null, ClassFilter.CLASSES_ONLY);
    for (Class<?> clazz : classes) {
        Constructor<?> constructor = clazz.getConstructor();
        Set<String> fieldNames = new HashSet<String>();
        for (Field field : clazz.getDeclaredFields()) {
            fieldNames.add(field.getName().toLowerCase());
        }
        Object voInstance = constructor.newInstance();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if ((method.getModifiers() & Modifier.PRIVATE) == Modifier.PRIVATE
                    || commonMethodNames.contains(method.getName())) {
                continue;
            }
            methodNames = allowedMethodNames.get(clazz);
            if (allowedMethodNames.get(clazz) != null
                    && allowedMethodNames.get(clazz).contains(
                            method.getName())) {
                continue;
            }

            if (method.getName().startsWith("is")) {
                if (!fieldNames.contains(method.getName().substring(2)
                        .toLowerCase())) {
                    errors.append("Missing property for method '"
                            + method.getName() + "' in type '"
                            + voInstance.getClass().getName() + "'\n");
                }
            } else if (method.getName().startsWith("set")) {
                if (!fieldNames.contains(method.getName().substring(3)
                        .toLowerCase())) {
                    errors.append("Missing property for method '"
                            + method.getName() + "' in type '"
                            + voInstance.getClass().getName() + "'\n");
                }
            } else if (method.getName().startsWith("get")) {
                if (!fieldNames.contains(method.getName().substring(3)
                        .toLowerCase())) {
                    errors.append("Missing property for method '"
                            + method.getName() + "' in type '"
                            + voInstance.getClass().getName() + "'\n");
                }
            } else {
                errors.append("Wrong method name '" + method.getName()
                        + "' in type '" + voInstance.getClass().getName()
                        + "'\n");
            }
        }
    }
    if (errors.length() > 0) {
        Assert.fail("\n" + errors.toString());
    }
}
 
Example 19
Source File: FieldFragment.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
public FieldFragment(HDType type, String name, CharSequence assignment) {
    super(Modifier.PRIVATE);
    this.type = type;
    this.name = name;
    this.assignmentFragment = new AssignmentFragment(assignment);
}
 
Example 20
Source File: GeciReflectionTools.java    From javageci with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a string that contains lower case letter Java modifiers comma separated into an access mask.
 *
 * @param masks  is the comma separated list of modifiers. The list can also contain the word {@code package}
 *               that will be translated to {@link GeciReflectionTools#PACKAGE} since there is no modifier {@code package}
 *               in Java.
 * @param dfault the mask to return in case the {@code includes} string is empty.
 * @return the mask converted from String
 */
public static int mask(String masks, int dfault) {
    int modMask = 0;
    if (masks == null) {
        return dfault;
    } else {
        for (var maskString : masks.split(",", -1)) {
            var maskTrimmed = maskString.trim();
            switch (maskTrimmed) {

                case "private":
                    modMask |= Modifier.PRIVATE;
                    break;
                case "public":
                    modMask |= Modifier.PUBLIC;
                    break;
                case "protected":
                    modMask |= Modifier.PROTECTED;
                    break;
                case "static":
                    modMask |= Modifier.STATIC;
                    break;
                case "package":
                    modMask |= GeciReflectionTools.PACKAGE;//reuse the bit
                    break;
                case "abstract":
                    modMask |= Modifier.ABSTRACT;
                    break;
                case "final":
                    modMask |= Modifier.FINAL;
                    break;
                case "interface":
                    modMask |= Modifier.INTERFACE;
                    break;
                case "synchronized":
                    modMask |= Modifier.SYNCHRONIZED;
                    break;
                case "native":
                    modMask |= Modifier.NATIVE;
                    break;
                case "transient":
                    modMask |= Modifier.TRANSIENT;
                    break;
                case "volatile":
                    modMask |= Modifier.VOLATILE;
                    break;
                default:
                    throw new IllegalArgumentException(maskTrimmed + " can not be used as a modifier string");
            }
        }
        return modMask;
    }
}