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

The following examples show how to use java.lang.reflect.Modifier#toString() . 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: LiveWeavingServiceImpl.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public List<MethodSignature> getMethodSignatures(String agentId, String className,
        String methodName) {
    if (methodName.contains("*") || methodName.contains("|")) {
        return ImmutableList.of();
    }
    List<UiAnalyzedMethod> analyzedMethods = getAnalyzedMethods(className, methodName);
    List<MethodSignature> methodSignatures = Lists.newArrayList();
    for (UiAnalyzedMethod analyzedMethod : analyzedMethods) {
        MethodSignature.Builder builder = MethodSignature.newBuilder();
        builder.setName(analyzedMethod.name());
        builder.addAllParameterType(analyzedMethod.parameterTypes());
        builder.setReturnType(analyzedMethod.returnType());
        // strip final and synchronized from displayed modifiers since they have no impact on
        // the weaver's method matching
        int reducedModifiers = analyzedMethod.modifiers() & ~ACC_FINAL & ~ACC_SYNCHRONIZED;
        String modifierNames = Modifier.toString(reducedModifiers);
        for (String modifier : splitter.split(modifierNames)) {
            builder.addModifier(modifier.toLowerCase(Locale.ENGLISH));
        }
        methodSignatures.add(builder.build());
    }
    return methodSignatures;
}
 
Example 2
Source File: MethodDeclaration.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void accept(ExpressionWriter writer) {
  String modifiers = Modifier.toString(modifier);
  writer.append(modifiers);
  if (!modifiers.isEmpty()) {
    writer.append(' ');
  }
  writer
      .append(resultType)
      .append(' ')
      .append(name)
      .list("(", ", ", ")",
          Lists.transform(parameters, ParameterExpression::declString))
      .append(' ')
      .append(body);
  writer.newlineAndIndent();
}
 
Example 3
Source File: BaseHelperAdapter.java    From CrazyDaily with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private VH createGenericKInstance(Class z, View view) {
    try {
        Constructor constructor;
        String buffer = Modifier.toString(z.getModifiers());
        String className = z.getName();
        if (className.contains("$") && !buffer.contains("static")) {
            constructor = z.getDeclaredConstructor(getClass(), View.class);
            return (VH) constructor.newInstance(this, view);
        } else {
            constructor = z.getDeclaredConstructor(View.class);
            return (VH) constructor.newInstance(view);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Source File: ClassUtil.java    From utils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取对象的全部protected类型方法.
 *
 * @param className     需要获取的类名
 * @param extendsMethod 是否获取继承来的方法
 * @return 方法名数组
 */
public static String[] getProtectedMethod(String className, boolean extendsMethod) {
    Class classz = loadClass(className);
    Method[] methods;
    if (extendsMethod) {
        methods = classz.getMethods();
    } else {
        methods = classz.getDeclaredMethods();
    }
    Set<String> set = new HashSet<>();
    if (methods != null) {
        for (Method f : methods) {
            String modifier = Modifier.toString(f.getModifiers());
            if (modifier.startsWith("protected")) {
                set.add(f.getName());
            }
        }
    }
    return set.toArray(new String[set.size()]);
}
 
Example 5
Source File: ClassUtil.java    From utils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取对象的全部public类型方法.
 *
 * @param className     需要获取的类名
 * @param extendsMethod 是否获取继承来的方法
 * @return 方法名数组
 */
public static String[] getPublicMethod(String className, boolean extendsMethod) {
    Class classz = loadClass(className);
    Method[] methods;
    if (extendsMethod) {
        methods = classz.getMethods();
    } else {
        methods = classz.getDeclaredMethods();
    }
    Set<String> set = new HashSet<>();
    if (methods != null) {
        for (Method f : methods) {
            String modifier = Modifier.toString(f.getModifiers());
            if (modifier.startsWith("public")) {
                set.add(f.getName());
            }
        }
    }
    return set.toArray(new String[set.size()]);
}
 
Example 6
Source File: ModifierUtil.java    From kalang with MIT License 6 votes vote down vote up
private static int addModifier(int modifiers, int singleModifier) throws InvalidModifierException {
    if ((modifiers & singleModifier) > 0) {
        throw new InvalidModifierException("repeat modifiers:" + Modifier.toString(singleModifier));
    }
    int result = modifiers | singleModifier;
    boolean isPublic = Modifier.isPublic(result);
    boolean isPrivate = Modifier.isPrivate(result);
    boolean isProtected = Modifier.isProtected(result);
    if (isPublic && isPrivate) {
        throw new InvalidModifierException("invalid combination of modifiers:public private");
    }
    if (isPublic && isProtected) {
        throw new InvalidModifierException("invalid combination of modifiers:public protected");
    }
    if (isProtected && isPrivate) {
        throw new InvalidModifierException("invalid combination of modifiers:protected private");
    }
    return result;
}
 
Example 7
Source File: BaseAdapter.java    From MultiTypeRecyclerViewAdapter with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private VH createGenericKInstance(Class z, View view) {
    try {
        Constructor constructor;
        String buffer = Modifier.toString(z.getModifiers());
        String className = z.getName();
        if (className.contains("$") && !buffer.contains("static")) {
            constructor = z.getDeclaredConstructor(getClass(), View.class);
            return (VH) constructor.newInstance(this, view);
        } else {
            constructor = z.getDeclaredConstructor(View.class);
            return (VH) constructor.newInstance(view);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Source File: ClassFieldDescription.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
/**
 * @return the full modifier string (cached)
 */
public String getModifierString() {
    if (modifierStr == null) {
        // initialise only on a need to basis
        // for performance reasons
        modifierStr = Modifier.toString(modifierID);
    }
    return modifierStr;
}
 
Example 9
Source File: FieldDeclaration.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void accept(ExpressionWriter writer) {
  String modifiers = Modifier.toString(modifier);
  writer.append(modifiers);
  if (!modifiers.isEmpty()) {
    writer.append(' ');
  }
  writer.append(parameter.type).append(' ').append(parameter.name);
  if (initializer != null) {
    writer.append(" = ").append(initializer);
  }
  writer.append(';');
  writer.newlineAndIndent();
}
 
Example 10
Source File: Inspector.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected String[] methodInfo(Constructor ctor) {
    String[] result = new String[MEMBER_EXCEPTIONS_IDX + 1];
    result[MEMBER_ORIGIN_IDX] = JAVA;
    result[MEMBER_MODIFIER_IDX] = Modifier.toString(ctor.getModifiers());
    result[MEMBER_DECLARER_IDX] = shortName(ctor.getDeclaringClass());
    result[MEMBER_TYPE_IDX] = shortName(ctor.getDeclaringClass());
    result[MEMBER_NAME_IDX] = ctor.getName();
    result[MEMBER_PARAMS_IDX] = makeParamsInfo(ctor.getParameterTypes());
    result[MEMBER_EXCEPTIONS_IDX] = makeExceptionInfo(ctor.getExceptionTypes());

    return withoutNulls(result);
}
 
Example 11
Source File: ClassDescription.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void processType(Member type) {
	super.addTitle("Member");
	super.addField("name", type.getName());
	super.addField("declaringClass", type.getDeclaringClass());
	super.addField("modifiers", Modifier.toString(type.getModifiers()));
	super.addField("synthetic", type.isSynthetic());
}
 
Example 12
Source File: ClassUtil.java    From utils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取对象的全部private类型方法.
 *
 * @param className 需要获取的类名
 * @return 方法名数组
 */
public static String[] getPrivateMethod(String className) {
    Class classz = loadClass(className);
    Method[] methods = classz.getDeclaredMethods();
    Set<String> set = new HashSet<>();
    if (methods != null) {
        for (Method f : methods) {
            String modifier = Modifier.toString(f.getModifiers());
            if (modifier.startsWith("private")) {
                set.add(f.getName());
            }
        }
    }
    return set.toArray(new String[set.size()]);
}
 
Example 13
Source File: ReflectionTest.java    From java-core-learning-example with Apache License 2.0 5 votes vote down vote up
/**
 * 打印对象所有的方法
 * @param cl
 */
public static void printMethods(Class cl){
    // 获取类所有方法对象数组
    Method[] methods = cl.getMethods();
    for (Method m : methods) {
        // 获取方法返回对象
        Class retType = m.getReturnType();
        String name = m.getName();

        System.out.print("   ");
        // 获取Java语言的修饰符
        // 修饰符由 Java 虚拟机的 public、protected、private、
        // final、static、abstract 和 interface 对应的常量组成;
        String modifiers = Modifier.toString(cl.getModifiers());
        if (modifiers.length() > 0)
            System.out.print(modifiers + " ");
        System.out.print(retType.getName() +" " + name + "(");

        // 获取方法的参数对象列表数组
        Class[] paramTypes = m.getParameterTypes();
        for (int i = 0; i < paramTypes.length;i++){
            if (i > 0)
                System.out.print(", ");
            System.out.print(paramTypes[i].getName());
        }
        System.out.println(");");
    }
}
 
Example 14
Source File: ClassUtil.java    From utils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取类中定义的private类型的属性字段.
 *
 * @param className 需要获取的类名
 * @return private类型的属性字段数组
 */
public static String[] getPrivateField(String className) {
    Class classz = loadClass(className);
    Set<String> set = new HashSet<>();
    Field[] fields = classz.getDeclaredFields();
    if (fields != null) {
        for (Field f : fields) {
            String modifier = Modifier.toString(f.getModifiers());
            if (modifier.startsWith("private")) {
                set.add(f.getName());
            }
        }
    }
    return set.toArray(new String[set.size()]);
}
 
Example 15
Source File: DeclarationStatement.java    From Quicksql with MIT License 5 votes vote down vote up
@Override void accept0(ExpressionWriter writer) {
  final String modifiers = Modifier.toString(this.modifiers);
  if (!modifiers.isEmpty()) {
    writer.append(modifiers).append(' ');
  }
  writer.append(parameter.type).append(' ').append(parameter.name);
  if (initializer != null) {
    writer.append(" = ").append(initializer);
  }
  writer.append(';');
  writer.newlineAndIndent();
}
 
Example 16
Source File: VerifyAccess.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Evaluate the JVM linkage rules for access to the given method
 * on behalf of a caller class which proposes to perform the access.
 * Return true if the caller class has privileges to invoke a method
 * or access a field with the given properties.
 * This requires an accessibility check of the referencing class,
 * plus an accessibility check of the member within the class,
 * which depends on the member's modifier flags.
 * <p>
 * The relevant properties include the defining class ({@code defc})
 * of the member, and its modifier flags ({@code mods}).
 * Also relevant is the class used to make the initial symbolic reference
 * to the member ({@code refc}).  If this latter class is not distinguished,
 * the defining class should be passed for both arguments ({@code defc == refc}).
 * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
 * A field or method R is accessible to a class or interface D if
 * and only if any of the following conditions is true:<ul>
 * <li>R is public.
 * <li>R is protected and is declared in a class C, and D is either
 *     a subclass of C or C itself.  Furthermore, if R is not
 *     static, then the symbolic reference to R must contain a
 *     symbolic reference to a class T, such that T is either a
 *     subclass of D, a superclass of D or D itself.
 * <li>R is either protected or has default access (that is,
 *     neither public nor protected nor private), and is declared
 *     by a class in the same runtime package as D.
 * <li>R is private and is declared in D.
 * </ul>
 * This discussion of access control omits a related restriction
 * on the target of a protected field access or method invocation
 * (the target must be of class D or a subtype of D). That
 * requirement is checked as part of the verification process
 * (5.4.1); it is not part of link-time access control.
 * @param refc the class used in the symbolic reference to the proposed member
 * @param defc the class in which the proposed member is actually defined
 * @param mods modifier flags for the proposed member
 * @param lookupClass the class for which the access check is being made
 * @return true iff the the accessing class can access such a member
 */
public static boolean isMemberAccessible(Class<?> refc,  // symbolic ref class
                                         Class<?> defc,  // actual def class
                                         int      mods,  // actual member mods
                                         Class<?> lookupClass,
                                         int      allowedModes) {
    if (allowedModes == 0)  return false;
    assert((allowedModes & PUBLIC) != 0 &&
           (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
    // The symbolic reference class (refc) must always be fully verified.
    if (!isClassAccessible(refc, lookupClass, allowedModes)) {
        return false;
    }
    // Usually refc and defc are the same, but verify defc also in case they differ.
    if (defc == lookupClass &&
        (allowedModes & PRIVATE) != 0)
        return true;        // easy check; all self-access is OK
    switch (mods & ALL_ACCESS_MODES) {
    case PUBLIC:
        return true;  // already checked above
    case PROTECTED:
        if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
            isSamePackage(defc, lookupClass))
            return true;
        if ((allowedModes & PROTECTED) == 0)
            return false;
        if ((mods & STATIC) != 0 &&
            !isRelatedClass(refc, lookupClass))
            return false;
        if ((allowedModes & PROTECTED) != 0 &&
            isSuperClass(defc, lookupClass))
            return true;
        return false;
    case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
        return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
                isSamePackage(defc, lookupClass));
    case PRIVATE:
        // Loosened rules for privates follows access rules for inner classes.
        return (ALLOW_NESTMATE_ACCESS &&
                (allowedModes & PRIVATE) != 0 &&
                isSamePackageMember(defc, lookupClass));
    default:
        throw new IllegalArgumentException("bad modifiers: "+Modifier.toString(mods));
    }
}
 
Example 17
Source File: ClassDocImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return the modifier string for this class. If it's an interface
 * exclude 'abstract' keyword from the modifier string
 */
@Override
public String modifiers() {
    return Modifier.toString(modifierSpecifier());
}
 
Example 18
Source File: SarlFieldWriter.java    From sarl with Apache License 2.0 4 votes vote down vote up
@Override
protected String modifierString(MemberDoc member) {
	final int ms = member.modifierSpecifier();
	final int no = Modifier.FINAL | Modifier.NATIVE | Modifier.SYNCHRONIZED;
	return Modifier.toString(ms & ~no);
}
 
Example 19
Source File: ClassDescription.java    From ldp4j with Apache License 2.0 4 votes vote down vote up
@Override
protected void processType(Class<?> type) {
	super.addTitle("Class");
	super.addField("name", type.getName());
	super.addField("package", type.getPackage());
	super.addField("simple name", type.getSimpleName());
	super.addField("canonical name", type.getCanonicalName());
	super.addField("interface", type.isInterface());
	super.addField("annotation", type.isAnnotation());
	super.addField("primitive", type.isPrimitive());
	super.addField("enum", type.isEnum());
	super.addMultiField("enum constants", type.getEnumConstants());
	super.addField("array", type.isArray());
	super.addField("component type", type.getComponentType());
	super.addField("anonymous class", type.isAnonymousClass());
	super.addField("local class", type.isLocalClass());
	super.addField("member class", type.isMemberClass());
	super.addField("declaring class", type.getDeclaringClass());
	super.addField("modifiers", Modifier.toString(type.getModifiers()));
	super.addField("synthetic", type.isSynthetic());
	super.addField("enclosing method", type.getEnclosingMethod());
	super.addField("enclosing constructor", type.getEnclosingConstructor());
	super.addField("enclosing class", type.getEnclosingClass());
	super.addBlockField("generic declaration", wrapElementAs(type,GenericDeclaration.class));
	super.addBlockField("annotated element", wrapElementAs(type,AnnotatedElement.class));

	Class<?> superclass=type.getSuperclass();
	if(superclass!=null) {
		if(!superclass.equals(Object.class) || !ignoreDefaultSuperclass) {
			if(traverseSuperclass) {
				super.addBlockField("superclass", wrap(type.getSuperclass()));
			} else {
				super.addField("superclass", type.getSuperclass());
			}
		}
	}
	super.addBlockField("generic superclass", wrapElement(type.getGenericSuperclass()));

	if(traverseInterfaces) {
		super.addMultiField("interfaces", wrap(type.getInterfaces()));
	} else {
		super.addMultiField("interfaces", type.getInterfaces());
	}
	super.addMultiField("generic interfaces", wrapElementArray(type.getGenericInterfaces()));

	String suffix="";
	String prefix="";
	if(excludePublicElementsFromDeclared()) {
		suffix=" (excluding public)";
		prefix="public ";
	}

	Class<?>[] classes = type.getClasses();
	List<Class<?>> declaredClasses = publicElementFilter(classes,type.getDeclaredClasses(),excludePublicElementsFromDeclared());
	if(traverseClasses) {
		super.addMultiField(prefix+"classes", wrap(classes));
		super.addMultiField("declared classes"+suffix, wrap(declaredClasses.toArray(new Class[]{})));
	} else {
		super.addMultiField(prefix+"classes", classes);
		super.addMultiField("declared classes"+suffix, declaredClasses);
	}
	Field[] fields = type.getFields();
	super.addMultiField(prefix+"fields", wrapElementArray(fields));
	super.addMultiField("declared fields"+suffix, wrapElements(publicElementFilter(fields,type.getDeclaredFields(),excludePublicElementsFromDeclared())));

	Method[] methods = type.getMethods();
	String subprefix="";
	if(ignoreDefaultMethods) {
		subprefix="non-default ";
	}

	super.addMultiField(prefix+subprefix+"methods", defaultMethodFilter(Arrays.asList(methods),ignoreDefaultMethods));
	super.addMultiField(prefix+subprefix+"declared methods"+suffix, defaultMethodFilter(publicElementFilter(methods,type.getDeclaredMethods(),excludePublicElementsFromDeclared()),ignoreDefaultMethods));

	Constructor<?>[] constructors=type.getConstructors();
	super.addMultiField(prefix+"constructors", wrapElementArray(constructors));
	super.addMultiField("declared constructors"+suffix, wrapElements(publicElementFilter(constructors,type.getDeclaredConstructors(),excludePublicElementsFromDeclared())));
}
 
Example 20
Source File: ParameterExpression.java    From Quicksql with MIT License 4 votes vote down vote up
String declString(Type type) {
  final String modifiers = Modifier.toString(modifier);
  return modifiers + (modifiers.isEmpty() ? "" : " ") + Types.className(type)
      + " " + name;
}