List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java
private Object instantiate(Class<?> customSerializer, Class<?> instanceClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SerializationException { if (customSerializer != null) { for (Method method : customSerializer.getMethods()) { if ("instantiate".equals(method.getName())) { return method.invoke(null, this); }/* ww w . j a va 2s . c o m*/ } // Ok to not have one. } if (instanceClass.isArray()) { int length = readInt(); // We don't pre-allocate the array; this prevents an allocation attack return new BoundedList<Object>(instanceClass.getComponentType(), length); } else if (instanceClass.isEnum()) { Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants(); int ordinal = readInt(); assert (ordinal >= 0 && ordinal < enumConstants.length); return enumConstants[ordinal]; } else { Constructor<?> constructor = instanceClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } }
From source file:com.nginious.http.serialize.JsonDeserializerCreator.java
/** * Creates a JSON deserializer for the specified bean class unless a deserializer has already * been created. Created deserializers are cached and returned on subsequent calls to this method. * //from w ww .j av a 2 s . c o m * @param <T> class type for bean * @param beanClazz bean class for which a deserializer should be created * @return the created deserializer * @throws SerializerFactoryException if unable to create deserializer or class is not a bean */ @SuppressWarnings("unchecked") protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException { JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } try { synchronized (this) { deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } checkDeserializability(beanClazz, "json"); String intBeanClazzName = Serialization.createInternalClassName(beanClazz); Method[] methods = beanClazz.getMethods(); String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer") .toString(); // Create class ClassWriter writer = new ClassWriter(0); String signature = Serialization .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature, "com/nginious/http/serialize/JsonDeserializer", null); // Create constructor Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer"); // Create deserialize method MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName); for (Method method : methods) { Serializable info = method.getAnnotation(Serializable.class); boolean canDeserialize = info == null || (info != null && info.deserialize() && info.types().indexOf("json") > -1); if (canDeserialize && method.getName().startsWith("set") && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> parameterType = parameterTypes[0]; if (parameterType.isArray()) { Class<?> arrayType = parameterType.getComponentType(); if (arrayType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName()); } else if (arrayType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName()); } else if (arrayType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName()); } else if (arrayType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName()); } else if (arrayType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName()); } else if (arrayType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName()); } else if (arrayType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;", intBeanClazzName, method.getName()); } } else if (parameterType.isPrimitive()) { if (parameterType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName()); } else if (parameterType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDouble", "D", "D", intBeanClazzName, method.getName()); } else if (parameterType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloat", "F", "F", intBeanClazzName, method.getName()); } else if (parameterType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeInt", "I", "I", intBeanClazzName, method.getName()); } else if (parameterType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLong", "J", "J", intBeanClazzName, method.getName()); } else if (parameterType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShort", "S", "S", intBeanClazzName, method.getName()); } } else if (parameterType.equals(Calendar.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName, method.getName()); } else if (parameterType.equals(Date.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate", "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName()); } else if (parameterType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName()); } } } visitor.visitVarInsn(Opcodes.ALOAD, 3); visitor.visitInsn(Opcodes.ARETURN); visitor.visitMaxs(5, 4); visitor.visitEnd(); writer.visitEnd(); byte[] clazzBytes = writer.toByteArray(); ClassLoader controllerLoader = null; if (classLoader.hasLoaded(beanClazz)) { controllerLoader = beanClazz.getClassLoader(); } else { controllerLoader = this.classLoader; } Class<?> clazz = Serialization.loadClass(controllerLoader, intDeserializerClazzName.replace('/', '.'), clazzBytes); deserializer = (JsonDeserializer<T>) clazz.newInstance(); deserializers.put(beanClazz, deserializer); return deserializer; } } catch (IllegalAccessException e) { throw new SerializerFactoryException(e); } catch (InstantiationException e) { throw new SerializerFactoryException(e); } }
From source file:com.kjt.service.common.SoafwTesterMojo.java
private void genTest(String basedPath, String className) { // /*from w ww . j av a2 s . c o m*/ this.getLog().info("" + className + ""); Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; try { Class cls = cl.loadClass(className); String testJFileName = cls.getSimpleName() + "Test.java"; String pkgPath = cls.getPackage().getName().replace(".", File.separator); String testJFilePath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + pkgPath; int len = 0; Class[] inters = cls.getInterfaces(); if (inters == null || (len = inters.length) == 0) { return; } /** * package import */ StringBuffer jHeadBuf = createTestJHeadByClass(cls); StringBuffer testJBuf = new StringBuffer(); testJBuf.append(jHeadBuf); Map<String, String> methodDefs = new HashMap<String, String>(); for (int j = 0; j < len; j++) { /** * ? */ Class interCls = inters[j]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { this.getLog().info("?" + className + "Test?"); StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } testJBuf.append(methodBuf); } else { this.getLog().info(className + ""); } } String testJFile = testJBuf.append("}").toString(); if (hasmethod) { write(testJFilePath, testJFileName, testJFile); } } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }
From source file:nl.nikhef.eduroam.WiFiEduroam.java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // Last step for android 4.0 - 4.2, called from saveWifiConfig private void applyAndroid4_42EnterpriseSettings(WifiConfiguration currentConfig, HashMap<String, String> configMap) { // NOTE: This code is mighty ugly, but reflection is the only way to get the methods we need // Get the enterprise class via reflection Class<?>[] wcClasses = WifiConfiguration.class.getClasses(); Class<?> wcEnterpriseField = null; for (Class<?> wcClass : wcClasses) { if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME)) { wcEnterpriseField = wcClass; break; }/*from w w w . j a va 2 s. c o m*/ } if (wcEnterpriseField == null) { throw new RuntimeException("There is no enterprisefield class."); } // Get the setValue handler via reflection Method wcefSetValue = null; for (Method m : wcEnterpriseField.getMethods()) { if (m.getName().equals("setValue")) { wcefSetValue = m; break; } } if (wcefSetValue == null) { throw new RuntimeException("There is no setValue method."); } // Fill fields from the HashMap Field[] wcefFields = WifiConfiguration.class.getFields(); for (Field wcefField : wcefFields) { if (configMap.containsKey(wcefField.getName())) { try { wcefSetValue.invoke(wcefField.get(currentConfig), configMap.get(wcefField.getName())); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java
/** * Locates all of the {@link Actions} and {@link Action} annotations on methods within the Action * class and its parent classes./* w w w . ja va 2 s. c o m*/ * * @param actionClass The action class. * @return The list of annotations or an empty list if there are none. */ protected Map<String, List<Action>> getActionAnnotations(Class<?> actionClass) { Method[] methods = actionClass.getMethods(); Map<String, List<Action>> map = new HashMap<String, List<Action>>(); for (Method method : methods) { Actions actionsAnnotation = method.getAnnotation(Actions.class); if (actionsAnnotation != null) { List<Action> actions = checkActionsAnnotation(actionsAnnotation); map.put(method.getName(), actions); } else { Action ann = method.getAnnotation(Action.class); if (ann != null) { map.put(method.getName(), Arrays.asList(ann)); } } } return map; }
From source file:com.sawyer.advadapters.widget.JSONAdapter.java
/** * Scans all subclasses of this instance for any isFilteredOut methods and caches them for later * invocation./*from w w w . j av a 2s . co m*/ */ private void cacheSubclassFilteredMethods() { //Scan public methods first Class<?> c = this.getClass(); Method[] methods = c.getMethods(); for (Method m : methods) { String key = getFilterMethodKey(m); if (key != null) mFilterMethods.put(key, m); } //Scan non-public methods next while (!c.equals(JSONAdapter.class)) { methods = c.getDeclaredMethods(); for (Method m : methods) { String key = getFilterMethodKey(m); if (key != null) { m.setAccessible(true); mFilterMethods.put(key, m); } } c = c.getSuperclass(); } }
From source file:com.jsmartframework.web.manager.BeanHelper.java
void setBeanMethods(Class<?> clazz) { if (!beanMethods.containsKey(clazz)) { List<Method> postConstructs = new ArrayList<>(); List<Method> preDestroys = new ArrayList<>(); List<Method> postSubmits = new ArrayList<>(); List<Method> postActions = new ArrayList<>(); List<Method> preSubmits = new ArrayList<>(); List<Method> preActions = new ArrayList<>(); List<String> unescapes = new ArrayList<>(); List<Method> executeAccess = new ArrayList<>(); for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(PostConstruct.class)) { postConstructs.add(method); }//w ww. ja va 2s . c o m if (method.isAnnotationPresent(PreDestroy.class)) { preDestroys.add(method); } if (method.isAnnotationPresent(PostSubmit.class)) { postSubmits.add(method); } if (method.isAnnotationPresent(PostAction.class)) { postActions.add(method); } if (method.isAnnotationPresent(PreSubmit.class)) { preSubmits.add(method); } if (method.isAnnotationPresent(PreAction.class)) { preActions.add(method); } if (method.isAnnotationPresent(Unescape.class)) { Matcher matcher = SET_METHOD_PATTERN.matcher(method.getName()); if (matcher.find()) { unescapes.add(matcher.group(1)); } } if (method.isAnnotationPresent(ExecuteAccess.class)) { executeAccess.add(method); } } beanMethods.put(clazz, clazz.getMethods()); executeAccessMethods.put(clazz, executeAccess.toArray(new Method[executeAccess.size()])); postConstructMethods.put(clazz, postConstructs.toArray(new Method[postConstructs.size()])); preDestroyMethods.put(clazz, preDestroys.toArray(new Method[preDestroys.size()])); postSubmitMethods.put(clazz, postSubmits.toArray(new Method[postSubmits.size()])); postActionMethods.put(clazz, postActions.toArray(new Method[postActions.size()])); preSubmitMethods.put(clazz, preSubmits.toArray(new Method[preSubmits.size()])); preActionMethods.put(clazz, preActions.toArray(new Method[preActions.size()])); unescapeMethods.put(clazz, unescapes.toArray(new String[unescapes.size()])); } }
From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java
private List<IEntityArgumentGetter> createListGetters(String columnPrefix, Class entityClass, Map<String, Integer> types, ParameterConverterService converterService, int aParameterIndex) { List<IEntityArgumentGetter> getters = new LinkedList<IEntityArgumentGetter>(); for (Method method : entityClass.getMethods()) { if (method.isAnnotationPresent(Column.class)) { Column column = method.getAnnotation(Column.class); Assert.notNull(column, "Method " + method + " has no Column annotation"); Assert.hasText(column.name(), "Column annotation has no name parameter in method " + method); String columnName = columnPrefix + column.name(); Integer dataType = types.get(columnName); Assert.notNull(dataType,// w w w. j a v a 2 s. c om "No information about cPreparedSolumn " + columnName + " in method " + method); IParameterConverter paramConverter = converterService.getConverter(dataType, method.getReturnType()); aParameterIndex++; getters.add(new EntityArgumentGetter(method, paramConverter, new StatementArgument(columnName, aParameterIndex))); } else if (method.isAnnotationPresent(OneToOne.class) || method.isAnnotationPresent(ManyToOne.class)) { Class oneToOneClass = method.getReturnType(); if (method.isAnnotationPresent(JoinColumn.class)) { // table name JoinColumn joinColumn = method.getAnnotation(JoinColumn.class); Assert.hasText(joinColumn.table(), "JoinColumn annotation has no table parameter in method " + method); String tableName = joinColumn.table(); // List<IEntityArgumentGetter> oneToOneClassGetters = createListGetters(tableName + "_", oneToOneClass, types, converterService, aParameterIndex); for (IEntityArgumentGetter oneToOneClassGetter : oneToOneClassGetters) { EntityArgumentGetterOneToOne oneToOneConverter = new EntityArgumentGetterOneToOne(method, oneToOneClassGetter); getters.add(oneToOneConverter); } } } } return getters; }
From source file:com.tower.service.test.SoafwTesterMojo.java
/** * // w w w .j a v a 2s. com * @param className * */ private void appendTest(String className) { /** * ?? ?public * ?MojoExecutionException?????? */ try { Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; Map<String, String> methodDefs = new HashMap<String, String>(); Class cls = cl.loadClass(className);// Class[] inters = cls.getInterfaces(); int len = 0; if (inters == null || (len = inters.length) == 0) { return; } for (int i = 0; i < len; i++) { Class interCls = inters[i]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } } } Class tstCls = cl.loadClass(className + "Test");// Method[] methods = tstCls.getDeclaredMethods(); len = methods == null ? 0 : methods.length; this.getLog().info("" + tstCls.getSimpleName() + "?" + len); /** * ??public */ for (int m = 0; m < len; m++) { Method method = methods[m]; SoaFwTest test = method.getAnnotation(SoaFwTest.class); if (test == null) { this.getLog() .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest"); continue; } String id = test.id(); if (methodDefs.containsKey(id)) { methodDefs.remove(id); } } if ((len = methodDefs.size()) == 0) { return; } String[] methodImpls = new String[len]; methodDefs.keySet().toArray(methodImpls); // TODO ??? StringBuilder src = new StringBuilder(); String srcs = readTestSrc(className); int index = srcs.lastIndexOf("}"); // this.getLog().info(srcs); //this.getLog().info("lastIndexOf(}):" + index); String impls = srcs.substring(0, index - 1); src.append(impls); src.append("\n"); this.getLog().info("?: " + className + "Test"); StringBuilder appends = new StringBuilder(); this.getLog().info("?"); for (int i = 0; i < len; i++) { String methodId = methodImpls[i]; String method = methodDefs.get(methodId); appends.append(method); appends.append("\n"); } src.append(appends.toString()); src.append("}"); Package pkg = tstCls.getPackage(); String pkgName = pkg.getName(); String pkgPath = pkgName.replace(".", File.separator); String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java"; String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath; write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString()); } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }
From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java
@Override public void loadDocuments() throws GenerateException { Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>(); SwaggerConfig swaggerConfig = new SwaggerConfig(); swaggerConfig.setApiVersion(apiSource.getApiVersion()); swaggerConfig.setSwaggerVersion(SwaggerSpec.version()); List<ApiListingReference> apiListingReferences = new ArrayList<ApiListingReference>(); List<AuthorizationType> authorizationTypes = new ArrayList<AuthorizationType>(); //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value for (Class<?> c : apiSource.getValidClasses()) { RequestMapping requestMapping = (RequestMapping) c.getAnnotation(RequestMapping.class); String description = ""; if (c.isAnnotationPresent(Api.class)) { description = ((Api) c.getAnnotation(Api.class)).value(); }//from www. ja v a 2 s . co m if (requestMapping != null && requestMapping.value().length != 0) { //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError //This occurs when a class or method loaded by reflections contains a type that has no dependency try { resourceMap = analyzeController(c, resourceMap, description); List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods())); if (c.getSuperclass() != null) { mList.addAll(Arrays.asList(c.getSuperclass().getMethods())); } for (Method m : mList) { if (m.isAnnotationPresent(RequestMapping.class)) { RequestMapping methodReq = m.getAnnotation(RequestMapping.class); //isolate resource name - attempt first by the first part of the mapping if (methodReq != null && methodReq.value().length != 0) { for (int i = 0; i < methodReq.value().length; i++) { String resourceKey = ""; String resourceName = Utils.parseResourceName(methodReq.value()[i]); if (!(resourceName.equals(""))) { String version = Utils.parseVersion(requestMapping.value()[0]); //get version - first try by class mapping, then method if (version.equals("")) { //class mapping failed - use method version = Utils.parseVersion(methodReq.value()[i]); } resourceKey = Utils.createResourceKey(resourceName, version); if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put(resourceKey, new SpringResource(c, resourceName, resourceKey, description)); } resourceMap.get(resourceKey).addMethod(m); } } } } } } catch (NoClassDefFoundError e) { LOG.error(e.getMessage()); LOG.info(c.getName()); //exception occurs when a method type or annotation is not recognized by the plugin } catch (ClassNotFoundException e) { LOG.error(e.getMessage()); LOG.info(c.getName()); } } } for (String str : resourceMap.keySet()) { ApiListing doc = null; SpringResource resource = resourceMap.get(str); try { doc = getDocFromSpringResource(resource, swaggerConfig); setBasePath(doc.basePath()); } catch (Exception e) { LOG.error("DOC NOT GENERATED FOR: " + resource.getResourceName()); e.printStackTrace(); } if (doc == null) continue; ApiListingReference apiListingReference = new ApiListingReference(doc.resourcePath(), doc.description(), doc.position()); apiListingReferences.add(apiListingReference); acceptDocument(doc); } // sort apiListingRefernce by position Collections.sort(apiListingReferences, new Comparator<ApiListingReference>() { @Override public int compare(ApiListingReference o1, ApiListingReference o2) { if (o1 == null && o2 == null) return 0; if (o1 == null && o2 != null) return -1; if (o1 != null && o2 == null) return 1; return o1.position() - o2.position(); } }); serviceDocument = new ResourceListing(swaggerConfig.apiVersion(), swaggerConfig.swaggerVersion(), scala.collection.immutable.List .fromIterator(JavaConversions.asScalaIterator(apiListingReferences.iterator())), scala.collection.immutable.List.fromIterator( JavaConversions.asScalaIterator(authorizationTypes.iterator())), swaggerConfig.info()); }