protected PsmMethodAction(Class c, String m, Class[] argArray) { // This prevents IllegalAccessExceptions when attempting to // invoke methods on a class that is in another package and not // defined 'public'. if (!Modifier.isPublic(c.getModifiers())) { throw new IllegalPsmMethodActionException("Action class must be public."); } try { method = c.getMethod(m, argArray); } catch (NoSuchMethodException ex) { throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m); } // Check each exception this method declares thrown. If it declares // exceptions, and any of them are not runtime exceptions, abort. Class[] exceptionTypes = method.getExceptionTypes(); for (int i = 0; i < exceptionTypes.length; i++) { Class exceptionClass = exceptionTypes[i]; if (!RuntimeException.class.isAssignableFrom(exceptionClass)) { throw new IllegalPsmMethodActionException( "Method must not declare non-Runtime " + "exceptions."); } } // Ensure that the method returns PsmEvent if (PsmEvent.class != method.getReturnType()) { throw new IllegalPsmMethodActionException("Method return type must be PsmEvent"); } // Ensure that both the method is both public and static. if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) { throw new IllegalPsmMethodActionException("Method " + m + " must be static and public."); } }
public static void main(String[] args) { // read class name from command line args or user input String name; if (args.length > 0) name = args[0]; else { Scanner in = new Scanner(System.in); System.out.println("Enter class name (e.g. java.util.Date): "); name = in.next(); } try { // print class name and superclass name (if != Object) Class cl = Class.forName(name); Class supercl = cl.getSuperclass(); String modifiers = Modifier.toString(cl.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print("class " + name); if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName()); System.out.print("\n{\n"); printConstructors(cl); System.out.println(); printMethods(cl); System.out.println(); printFields(cl); System.out.println("}"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); }
public JavaType findType(String name) { if (_bindings == null) { _resolve(); } JavaType t = _bindings.get(name); if (t != null) { return t; } if (_placeholders != null && _placeholders.contains(name)) { return UNBOUND; } // New with 1.7: check parent context if (_parentBindings != null) { return _parentBindings.findType(name); } // nothing found, so... // Should we throw an exception or just return null? /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within * java.util, such as HashMap$KeySet; so let's punt the problem * (honestly not sure what to do -- they are unbound for good, I think) */ if (_contextClass != null) { Class<?> enclosing = _contextClass.getEnclosingClass(); if (enclosing != null) { // [JACKSON-572]: Actually, let's skip this for all non-static inner classes // (which will also cover 'java.util' type cases... if (!Modifier.isStatic(_contextClass.getModifiers())) { return UNBOUND; } // ... so this piece of code should not be needed any more /* Package pkg = enclosing.getPackage(); if (pkg != null) { // as per [JACKSON-533], also include "java.util.concurrent": if (pkg.getName().startsWith("java.util")) { return UNBOUND; } } */ } } String className; if (_contextClass != null) { className = _contextClass.getName(); } else if (_contextType != null) { className = _contextType.toString(); } else { className = "UNKNOWN"; } throw new IllegalArgumentException( "Type variable '" + name + "' can not be resolved (with context of class " + className + ")"); // t = UNBOUND; }
public static String isLocalType(Class<?> type) { /* As per [JACKSON-187], GAE seems to throw SecurityExceptions * here and there... and GAE itself has a bug, too * (see []). Bah. */ try { // one more: method locals, anonymous, are not good: if (type.getEnclosingMethod() != null) { return "local/anonymous"; } /* But how about non-static inner classes? Can't construct * easily (theoretically, we could try to check if parent * happens to be enclosing... but that gets convoluted) */ if (type.getEnclosingClass() != null) { if (!Modifier.isStatic(type.getModifiers())) { return "non-static member class"; } } } catch (SecurityException e) { } catch (NullPointerException e) { } return null; }
/** * Register a custom argument creator factory for an unknown final class * * @param clazz The class for which this factory should be used * @param creator The argument factory * @param <T> */ public static <T> void registerFinalClassArgumentCreator( Class<T> clazz, FinalClassArgumentCreator<T> creator) { if ((clazz.getModifiers() & Modifier.FINAL) == 0) throw new RuntimeException( "A custom argument creator can be registered only for final classes"); FINAL_CLASS_ARGUMENT_CREATORS.put(clazz, creator); }
@Nullable public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) { InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType); if (instanceFactory != null) { return instanceFactory; } Class<?> mockedClass = getClassType(mockedType); //noinspection ReuseOfLocalVariable instanceFactory = mockedTypesAndInstances.get(mockedClass); if (instanceFactory != null) { return instanceFactory; } boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers()); for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) { Type registeredMockedType = entry.getKey(); Class<?> registeredMockedClass = getClassType(registeredMockedType); if (abstractType) { registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass); } if (mockedClass.isAssignableFrom(registeredMockedClass)) { instanceFactory = entry.getValue(); break; } } return instanceFactory; }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
private <T> CachedRuleSource doExtract(final Class<T> source) { final ModelType<T> type = ModelType.of(source); DefaultMethodModelRuleExtractionContext context = new DefaultMethodModelRuleExtractionContext(type, this); // TODO - exceptions thrown here should point to some extensive documentation on the concept of // class rule sources StructSchema<T> schema = getSchema(source, context); if (schema == null) { throw new InvalidModelRuleDeclarationException(context.problems.format()); } // sort for determinism Set<Method> methods = new TreeSet<Method>(Ordering.usingToString()); methods.addAll(Arrays.asList(source.getDeclaredMethods())); ImmutableList.Builder<ModelProperty<?>> implicitInputs = ImmutableList.builder(); ModelProperty<?> target = null; for (ModelProperty<?> property : schema.getProperties()) { if (property.isAnnotationPresent(RuleTarget.class)) { target = property; } else if (property.isAnnotationPresent(RuleInput.class) && !(property.getSchema() instanceof ScalarValueSchema)) { implicitInputs.add(property); } for (WeaklyTypeReferencingMethod<?, ?> method : property.getAccessors()) { methods.remove(method.getMethod()); } } ImmutableList.Builder<ExtractedRuleDetails> rules = ImmutableList.builder(); for (Method method : methods) { MethodRuleDefinition<?, ?> ruleDefinition = DefaultMethodRuleDefinition.create(source, method); ExtractedModelRule rule = getMethodHandler(ruleDefinition, method, context); if (rule != null) { rules.add(new ExtractedRuleDetails(ruleDefinition, rule)); } } if (context.hasProblems()) { throw new InvalidModelRuleDeclarationException(context.problems.format()); } StructBindings<T> bindings = structBindingsStore.getBindings(schema); if (schema.getProperties().isEmpty()) { return new StatelessRuleSource( rules.build(), Modifier.isAbstract(source.getModifiers()) ? new AbstractRuleSourceFactory<T>(schema, bindings, proxyFactory) : new ConcreteRuleSourceFactory<T>(type)); } else { return new ParameterizedRuleSource( rules.build(), target, implicitInputs.build(), schema, bindings, proxyFactory); } }
/** * Checks if a class fulfills the JavaBeans contract. * * @param cls the class to check */ public static void checkJavaBean(Class<?> cls) { try { Constructor<?> constructor = cls.getDeclaredConstructor(); int classModifiers = cls.getModifiers(); if (Modifier.isInterface(classModifiers)) throw new RuntimeException(cls.getName() + " is an interface"); if (Modifier.isAbstract(classModifiers)) throw new RuntimeException( cls.getName() + " cannot be instantiated - it is an abstract class"); int modifiers = constructor.getModifiers(); if (!Modifier.isPublic(modifiers)) throw new RuntimeException("No public default constructor in " + cls); } catch (NoSuchMethodException e) { throw new RuntimeException("No default constructor in class " + cls); } catch (SecurityException e) { logger.error( "I am not allowed to check the class by using reflection, " + "so I just can hope the class is alright and go on: ", e); } }
/** * Return true if the type is not abstract and not an interface, and has a constructor annotated * with {@link Inject} or its only constructor is the default constructor. * * @param type A class type * @return True if the class type is instantiable */ public static boolean isInstantiable(Class<?> type) { if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()) { // first check for a constructor annotated with @Inject, // - this doesn't care how many we'll let the injector complain // if there are more than one for (Constructor<?> c : type.getDeclaredConstructors()) { if (c.getAnnotation(Inject.class) != null) { return true; } } // check if we only have the public default constructor if (type.getConstructors().length == 1 && type.getConstructors()[0].getParameterTypes().length == 0) { return true; } } // no constructor available return false; }
// Other notes to implementors: // <p> // No stable mapping is promised between the single-method interface and // the implementation class C. Over time, several implementation // classes might be used for the same type. // <p> // If the implementation is able // to prove that a wrapper of the required type // has already been created for a given // method handle, or for another method handle with the // same behavior, the implementation may return that wrapper in place of // a new wrapper. // <p> // This method is designed to apply to common use cases // where a single method handle must interoperate with // an interface that implements a function-like // API. Additional variations, such as single-abstract-method classes with // private constructors, or interfaces with multiple but related // entry points, must be covered by hand-written or automatically // generated adapter classes. // public static <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) { if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers())) throw new IllegalArgumentException("not a public interface: " + intfc.getName()); final Method[] methods = getSingleNameMethods(intfc); if (methods == null) throw new IllegalArgumentException("not a single-method interface: " + intfc.getName()); final MethodHandle[] vaTargets = new MethodHandle[methods.length]; for (int i = 0; i < methods.length; i++) { Method sm = methods[i]; MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes()); MethodHandle checkTarget = target.asType(smMT); // make throw WMT checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class)); vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount()); } return intfc.cast( Proxy.newProxyInstance( intfc.getClassLoader(), new Class[] {intfc, WrapperInstance.class}, new InvocationHandler() { private Object getArg(String name) { if ((Object) name == "getWrapperInstanceTarget") return target; if ((Object) name == "getWrapperInstanceType") return intfc; throw new AssertionError(); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (int i = 0; i < methods.length; i++) { if (method.equals(methods[i])) return vaTargets[i].invokeExact(args); } if (method.getDeclaringClass() == WrapperInstance.class) return getArg(method.getName()); if (isObjectMethod(method)) return callObjectMethod(this, method, args); throw new InternalError("bad proxy method: " + method); } })); }
@Override public int getModifiers() { return _class.getModifiers(); }
/** Calculates a MD5 digest of the class. */ public String getDigest() { try { if (_className == null || "".equals(_className)) return ""; DynamicClassLoader loader = (DynamicClassLoader) Thread.currentThread().getContextClassLoader(); ClassLoader tmpLoader = loader.getNewTempClassLoader(); Class cl = Class.forName(_className, false, tmpLoader); if (cl == null) return ""; MessageDigest digest = MessageDigest.getInstance("MD5"); addDigest(digest, cl.getName()); addDigest(digest, cl.getModifiers()); Class superClass = cl.getSuperclass(); if (superClass != null) addDigest(digest, superClass.getName()); Class[] interfaces = cl.getInterfaces(); for (int i = 0; i < interfaces.length; i++) addDigest(digest, interfaces[i].getName()); Field[] fields = cl.getDeclaredFields(); Arrays.sort(fields, new FieldComparator()); if (_checkFields) { for (Field field : fields) { if (Modifier.isPrivate(field.getModifiers()) && !_checkPrivate) continue; if (Modifier.isProtected(field.getModifiers()) && !_checkProtected) continue; addDigest(digest, field.getName()); addDigest(digest, field.getModifiers()); addDigest(digest, field.getType().getName()); addDigest(digest, field.getAnnotations()); } } Method[] methods = cl.getDeclaredMethods(); Arrays.sort(methods, new MethodComparator()); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (Modifier.isPrivate(method.getModifiers()) && !_checkPrivate) continue; if (Modifier.isProtected(method.getModifiers()) && !_checkProtected) continue; if (Modifier.isStatic(method.getModifiers()) && !_checkStatic) continue; addDigest(digest, method.getName()); addDigest(digest, method.getModifiers()); addDigest(digest, method.getName()); Class[] param = method.getParameterTypes(); for (int j = 0; j < param.length; j++) addDigest(digest, param[j].getName()); addDigest(digest, method.getReturnType().getName()); Class[] exn = method.getExceptionTypes(); for (int j = 0; j < exn.length; j++) addDigest(digest, exn[j].getName()); addDigest(digest, method.getAnnotations()); } byte[] digestBytes = new byte[256]; int len = digest.digest(digestBytes, 0, digestBytes.length); return digestToBase64(digestBytes, len); } catch (Exception e) { log.log(Level.FINER, e.toString(), e); return ""; } }
private static void discoverAccessibleMethods( Class<?> clazz, Map<MethodSignature, Method> map, boolean includeProtected, boolean includePrivate) { if (Modifier.isPublic(clazz.getModifiers()) || includePrivate) { try { if (includeProtected || includePrivate) { while (clazz != null) { try { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; int mods = method.getModifiers(); if (Modifier.isPublic(mods) || Modifier.isProtected(mods) || includePrivate) { if (includePrivate) method.setAccessible(true); map.put(new MethodSignature(method), method); } } clazz = clazz.getSuperclass(); } catch (SecurityException e) { // Some security settings (i.e., applets) disallow // access to Class.getDeclaredMethods. Fall back to // Class.getMethods. Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; MethodSignature sig = new MethodSignature(method); if (map.get(sig) == null) map.put(sig, method); } break; // getMethods gets superclass methods, no // need to loop any more } } } else { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; MethodSignature sig = new MethodSignature(method); map.put(sig, method); } } return; } catch (SecurityException e) { Context.reportWarning( "Could not discover accessible methods of class " + clazz.getName() + " due to lack of privileges, " + "attemping superclasses/interfaces."); // Fall through and attempt to discover superclass/interface // methods } } Class<?>[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { discoverAccessibleMethods(interfaces[i], map, includeProtected, includePrivate); } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { discoverAccessibleMethods(superclass, map, includeProtected, includePrivate); } }
protected void loadHttpServlet(final AnyValue conf, final ClassFilter<? extends Servlet> filter) throws Exception { final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null; final String prefix = conf == null ? "" : conf.getValue("path", ""); final String threadName = "[" + Thread.currentThread().getName() + "] "; List<FilterEntry<? extends Servlet>> list = new ArrayList(filter.getFilterEntrys()); list.sort( (FilterEntry<? extends Servlet> o1, FilterEntry<? extends Servlet> o2) -> { // 必须保证WebSocketServlet优先加载, 因为要确保其他的HttpServlet可以注入本地模式的WebSocketNode boolean ws1 = WebSocketServlet.class.isAssignableFrom(o1.getType()); boolean ws2 = WebSocketServlet.class.isAssignableFrom(o2.getType()); if (ws1 == ws2) return o1.getType().getName().compareTo(o2.getType().getName()); return ws1 ? -1 : 1; }); final List<AbstractMap.SimpleEntry<String, String[]>> ss = sb == null ? null : new ArrayList<>(); for (FilterEntry<? extends Servlet> en : list) { Class<HttpServlet> clazz = (Class<HttpServlet>) en.getType(); if (Modifier.isAbstract(clazz.getModifiers())) continue; WebServlet ws = clazz.getAnnotation(WebServlet.class); if (ws == null || ws.value().length == 0) continue; final HttpServlet servlet = clazz.newInstance(); resourceFactory.inject(servlet, this); final String[] mappings = ws.value(); String pref = ws.repair() ? prefix : ""; DefaultAnyValue servletConf = (DefaultAnyValue) en.getProperty(); WebInitParam[] webparams = ws.initParams(); if (webparams.length > 0) { if (servletConf == null) servletConf = new DefaultAnyValue(); for (WebInitParam webparam : webparams) { servletConf.addValue(webparam.name(), webparam.value()); } } this.httpServer.addHttpServlet(servlet, pref, servletConf, mappings); if (ss != null) { for (int i = 0; i < mappings.length; i++) { mappings[i] = pref + mappings[i]; } ss.add(new AbstractMap.SimpleEntry<>(clazz.getName(), mappings)); } } if (ss != null) { Collections.sort( ss, (AbstractMap.SimpleEntry<String, String[]> o1, AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey())); int max = 0; for (AbstractMap.SimpleEntry<String, String[]> as : ss) { if (as.getKey().length() > max) max = as.getKey().length(); } for (AbstractMap.SimpleEntry<String, String[]> as : ss) { sb.append(threadName).append(" Loaded ").append(as.getKey()); for (int i = 0; i < max - as.getKey().length(); i++) { sb.append(' '); } sb.append(" mapping to ").append(Arrays.toString(as.getValue())).append(LINE_SEPARATOR); } } if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString()); }
/** * Return true if the type is not abstract and not an interface. This will return true essentially * when the class "should" have a default constructor or a constructor annotated with {@link * Inject @Inject} to be used properly. * * <p>As another special rule, if the input type is {@link Void}, false is returned because for * most intents and purposes, it is not instantiable. * * @param type The type to test * @return True if it should be instantiable */ public static boolean shouldBeInstantiable(Class<?> type) { return !Modifier.isAbstract(type.getModifiers()) && !type.isInterface() && !Void.class.equals(type); }
public static void main(String[] args) throws Exception { System.out.println( "Checking that all known MBeans that are " + "NotificationBroadcasters have sane " + "MBeanInfo.getNotifications()"); System.out.println("Checking platform MBeans..."); checkPlatformMBeans(); URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class"); if (codeBase == null) { throw new Exception("Could not determine codeBase for " + MBeanServer.class); } System.out.println(); System.out.println("Looking for standard MBeans..."); String[] classes = findStandardMBeans(codeBase); System.out.println("Testing standard MBeans..."); for (int i = 0; i < classes.length; i++) { String name = classes[i]; Class<?> c; try { c = Class.forName(name); } catch (Throwable e) { System.out.println(name + ": cannot load (not public?): " + e); continue; } if (!NotificationBroadcaster.class.isAssignableFrom(c)) { System.out.println(name + ": not a NotificationBroadcaster"); continue; } if (Modifier.isAbstract(c.getModifiers())) { System.out.println(name + ": abstract class"); continue; } NotificationBroadcaster mbean; Constructor<?> constr; try { constr = c.getConstructor(); } catch (Exception e) { System.out.println(name + ": no public no-arg constructor: " + e); continue; } try { mbean = (NotificationBroadcaster) constr.newInstance(); } catch (Exception e) { System.out.println(name + ": no-arg constructor failed: " + e); continue; } check(mbean); } System.out.println(); System.out.println("Testing some explicit cases..."); check(new RelationService(false)); /* We can't do this: check(new RequiredModelMBean()); because the Model MBean spec more or less forces us to use the names GENERIC and ATTRIBUTE_CHANGE for its standard notifs. */ checkRMIConnectorServer(); System.out.println(); if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious); if (failed.isEmpty()) System.out.println("TEST PASSED"); else { System.out.println("TEST FAILED: " + failed); System.exit(1); } }
private static Object createPlaceholder(Class<?> clazz, InvocationSequence invocationSequence) { return !Modifier.isFinal(clazz.getModifiers()) ? createProxy(new ProxyArgument(clazz, invocationSequence), clazz, false) : createArgumentPlaceholder(clazz); }
/** * Helper method that checks if given class is a concrete one; that is, not an interface or * abstract class. */ public static boolean isConcrete(Class<?> type) { int mod = type.getModifiers(); return (mod & (Modifier.INTERFACE | Modifier.ABSTRACT)) == 0; }