Java Code Examples for java.lang.reflect.Modifier
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.
Source file: IntrospectionSupport.java

private static void addFields(Object target,Class<?> startClass,Class<?> stopClass,LinkedHashMap<String,Object> map){ if (startClass != stopClass) { addFields(target,startClass.getSuperclass(),stopClass,map); } Field[] fields=startClass.getDeclaredFields(); for (int i=0; i < fields.length; i++) { Field field=fields[i]; if (Modifier.isStatic(field.getModifiers())) { continue; } try { field.setAccessible(true); Object o=field.get(target); if (o != null && o.getClass().isArray()) { try { o=Arrays.asList((Object[])o); } catch ( Throwable e) { } } map.put(field.getName(),o); } catch ( Throwable e) { e.printStackTrace(); } } }
Example 2
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/skillengine/loader/.
Source file: SkillHandlerLoader.java

public boolean isValidClass(Class<?> clazz){ final int modifiers=clazz.getModifiers(); if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)) return false; if (!Modifier.isPublic(modifiers)) return false; return true; }
Example 3
From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/.
Source file: ConfigurationMetadata.java

/** * Find methods that are tagged with a given annotation somewhere in the hierarchy * @param configClass the class to analyze * @return a map that associates a concrete method to the actual method tagged(which may belong to a different class in class hierarchy) */ private static Collection<Method> findAnnotatedMethods(Class<?> configClass,Class<? extends java.lang.annotation.Annotation> annotation){ List<Method> result=new ArrayList<Method>(); for ( Method method : configClass.getMethods()) { if (method.isSynthetic() || method.isBridge() || Modifier.isStatic(method.getModifiers())) { continue; } Method managedMethod=findAnnotatedMethod(configClass,annotation,method.getName(),method.getParameterTypes()); if (managedMethod != null) { result.add(managedMethod); } } return result; }
Example 4
From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/util/.
Source file: HelloWorldMaker.java

public static void main(String[] args) throws Exception { DexMaker dexMaker=new DexMaker(); TypeId<?> helloWorld=TypeId.get("LHelloWorld;"); dexMaker.declare(helloWorld,"HelloWorld.generated",Modifier.PUBLIC,TypeId.OBJECT); generateHelloMethod(dexMaker,helloWorld); File outputDir=Environment.getExternalStorageDirectory(); ClassLoader loader=dexMaker.generateAndLoad(HelloWorldMaker.class.getClassLoader(),outputDir); Class<?> helloWorldClass=loader.loadClass("HelloWorld"); Log.d("helloWorldClass.getMethod(\"hello\").invoke(null);"); helloWorldClass.getMethod("hello").invoke(null); }
Example 5
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/bean/.
Source file: PureJavaReflectionProvider.java

public Object newInstance(Class type){ try { Constructor[] constructors=type.getDeclaredConstructors(); for (int i=0; i < constructors.length; i++) { if (constructors[i].getParameterTypes().length == 0) { if (!Modifier.isPublic(constructors[i].getModifiers())) { constructors[i].setAccessible(true); } return constructors[i].newInstance(new Object[0]); } } if (Serializable.class.isAssignableFrom(type)) { return instantiateUsingSerialization(type); } else { throw new ObjectAccessException("Cannot construct " + type.getName() + " as it does not have a no-args constructor"); } } catch ( InstantiationException e) { throw new ObjectAccessException("Cannot construct " + type.getName(),e); } catch ( IllegalAccessException e) { throw new ObjectAccessException("Cannot construct " + type.getName(),e); } catch ( InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException)e.getTargetException(); } else if (e.getTargetException() instanceof Error) { throw (Error)e.getTargetException(); } else { throw new ObjectAccessException("Constructor for " + type.getName() + " threw an exception",e.getTargetException()); } } }
Example 6
From project amplafi-sworddance, under directory /src/main/java/com/sworddance/beans/.
Source file: ProxyMapperImpl.java

/** * @param method * @param args * @param actualObject * @return * @throws IllegalAccessException * @throws InvocationTargetException */ private Object doInvoke(Method method,Object[] args) throws IllegalAccessException, InvocationTargetException { O actualObject; if ((method.getModifiers() & Modifier.STATIC) != Modifier.STATIC) { actualObject=getRealObject(true,"need object to call a non-static method ",this," method=",method,"(",join(args),")"); } else { actualObject=null; } try { return method.invoke(actualObject,args); } catch ( RuntimeException e) { throw new InvocationTargetException(e,this + " method=" + method+ "("+ join(args)+ ")"); } }
Example 7
From project android-aac-enc, under directory /src/com/googlecode/mp4parser/boxes/mp4/objectdescriptors/.
Source file: ObjectDescriptorFactory.java

public static BaseDescriptor createFrom(int objectTypeIndication,ByteBuffer bb) throws IOException { int tag=IsoTypeReader.readUInt8(bb); Map<Integer,Class<? extends BaseDescriptor>> tagMap=descriptorRegistry.get(objectTypeIndication); if (tagMap == null) { tagMap=descriptorRegistry.get(-1); } Class<? extends BaseDescriptor> aClass=tagMap.get(tag); BaseDescriptor baseDescriptor; if (aClass == null || aClass.isInterface() || Modifier.isAbstract(aClass.getModifiers())) { log.warning("No ObjectDescriptor found for objectTypeIndication " + Integer.toHexString(objectTypeIndication) + " and tag "+ Integer.toHexString(tag)+ " found: "+ aClass); baseDescriptor=new UnknownDescriptor(); } else { try { baseDescriptor=aClass.newInstance(); } catch ( Exception e) { log.log(Level.SEVERE,"Couldn't instantiate BaseDescriptor class " + aClass + " for objectTypeIndication "+ objectTypeIndication+ " and tag "+ tag,e); throw new RuntimeException(e); } } baseDescriptor.parse(tag,bb); return baseDescriptor; }
Example 8
From project androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/.
Source file: RobolectricParameterized.java

private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception { List<FrameworkMethod> methods=testClass.getAnnotatedMethods(Parameters.class); for ( FrameworkMethod each : methods) { int modifiers=each.getMethod().getModifiers(); if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) return each; } throw new Exception("No public static parameters method on class " + testClass.getName()); }
Example 9
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: NLS.java

private static void computeMissingMessages(String bundleName,Class clazz,Map fieldMap,Field[] fieldArray,boolean isAccessible){ final int MOD_EXPECTED=Modifier.PUBLIC | Modifier.STATIC; final int MOD_MASK=MOD_EXPECTED | Modifier.FINAL; final int numFields=fieldArray.length; for (int i=0; i < numFields; i++) { Field field=fieldArray[i]; if ((field.getModifiers() & MOD_MASK) != MOD_EXPECTED) continue; if (fieldMap.get(field.getName()) == ASSIGNED) continue; try { String value="NLS missing message: " + field.getName() + " in: "+ bundleName; if (Debug.SHOW_FULL_DETAIL == 1) System.out.println(value); log(SEVERITY_WARNING,value,null); if (!isAccessible) field.setAccessible(true); field.set(null,value); } catch ( Exception e) { log(SEVERITY_ERROR,"Error setting the missing message value for: " + field.getName(),e); } } }
Example 10
From project anode, under directory /bridge-stub-generator/src/org/meshpoint/anode/stub/.
Source file: DictionaryStubGenerator.java

public void generate() throws IOException, GeneratorException { if ((iface.getModifiers() & Modifier.INTERFACE) != 0) throw new GeneratorException("ValueStubGenerator: class must not be an interface",null); if (iface.getOperations().length > 0) throw new GeneratorException("ValueStubGenerator: class must not have any operations",null); String className=iface.getStubClassname(); ClassWriter cw=new ClassWriter(className,StubUtil.MODE_DICT); try { writePreamble(cw,className,null,null,StubUtil.MODE_DICT); Attribute[] attributes=iface.getAttributes(); emitArgsArray(cw,attributes.length,true); cw.openScope("public static void __import(" + iface.getName() + " ob, Object[] vals)"); for (int i=0; i < attributes.length; i++) { Attribute attr=attributes[i]; if ((attr.modifiers & Modifier.STATIC) == 0) { registerName(attr.name); cw.writeln("ob." + attr.name + " = "+ getObjectToArgExpression(attr.type,"vals[" + i + "]")+ ";"); } } cw.closeScope(); cw.writeln(); cw.openScope("public static Object[] __export(" + iface.getName() + " ob)"); for (int i=0; i < attributes.length; i++) { Attribute attr=attributes[i]; if ((attr.modifiers & Modifier.STATIC) == 0) cw.writeln("__args[" + i + "] = "+ getArgToObjectExpression(attr.type,"ob." + attr.name)+ ";"); } cw.writeln("return __args;"); cw.closeScope(); cw.writeln(); cw.closeScope(); } finally { cw.close(); } }
Example 11
From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/nls/.
Source file: NLS.java

/** * Checks if the given field is an "NLS field". A NLS field must be public static and not final. * @param field the field to check * @return true if it is a "NLS field" that should be set to a localized value */ private static final boolean isNLSField(Field field){ int modifier=field.getModifiers(); String problem=null; if (!Modifier.isStatic(modifier)) { problem="not static"; } else if (Modifier.isFinal(modifier)) { problem="final"; } else if (!Modifier.isPublic(modifier)) { problem="not public"; } NLSMessage nlsMessage=field.getAnnotation(NLSMessage.class); if (problem != null) { if (nlsMessage == null) { return false; } throw new RuntimeException(String.format(MSG_MISUSEDNLSANNOTATION,field.getDeclaringClass().getName(),field.getName(),problem)); } return (nlsMessage != null) || (field.getType() == String.class) || ExceptionCode.class.isAssignableFrom(field.getType()); }
Example 12
From project any23, under directory /core/src/main/java/org/apache/any23/validator/.
Source file: XMLValidationReportSerializer.java

private List<Method> filterGetters(Class c){ Method[] methods=c.getDeclaredMethods(); List<Method> filtered=new ArrayList<Method>(); for ( Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { continue; } final String methodName=method.getName(); if (method.getParameterTypes().length == 0 && ((methodName.length() > 3 && methodName.indexOf("get") == 0) || (methodName.length() > 2 && methodName.indexOf("is") == 0))) { filtered.add(method); } } return filtered; }
Example 13
From project apb, under directory /modules/apb/src/apb/testrunner/.
Source file: JUnit3TestSet.java

@Nullable private static Method getSuiteMethod(Class<?> clazz){ final Method suiteMethod; try { suiteMethod=clazz.getMethod(SUITE_METHOD); } catch ( NoSuchMethodException ignore) { return null; } final int m=suiteMethod.getModifiers(); if (Modifier.isPublic(m) && Modifier.isStatic(m) && Test.class.isAssignableFrom(suiteMethod.getReturnType())) { return suiteMethod; } return null; }
Example 14
From project arquillian-core, under directory /container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/client/deployment/.
Source file: AnnotationDeploymentScenarioGenerator.java

private void validate(Method deploymentMethod){ if (!Modifier.isStatic(deploymentMethod.getModifiers())) { throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName() + " is not static. "+ deploymentMethod); } if (!Archive.class.isAssignableFrom(deploymentMethod.getReturnType()) && !Descriptor.class.isAssignableFrom(deploymentMethod.getReturnType())) { throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName() + " must have return type "+ Archive.class.getName()+ " or "+ Descriptor.class.getName()+ ". "+ deploymentMethod); } if (deploymentMethod.getParameterTypes().length != 0) { throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName() + " can not accept parameters. "+ deploymentMethod); } }
Example 15
From project arquillian-extension-android, under directory /android-configuration/src/main/java/org/jboss/arquillian/android/configuration/.
Source file: SecurityActions.java

static List<Field> getAccessableFields(final Class<?> source){ List<Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<List<Field>>(){ public List<Field> run(){ List<Field> foundFields=new ArrayList<Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.add(field); } return foundFields; } } ); return declaredAccessableFields; }
Example 16
From project arquillian-extension-drone, under directory /drone-configuration/src/main/java/org/jboss/arquillian/drone/configuration/.
Source file: SecurityActions.java

static Map<String,Field> getAccessableFields(final Class<?> source){ Map<String,Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<Map<String,Field>>(){ public Map<String,Field> run(){ Map<String,Field> foundFields=new LinkedHashMap<String,Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.put(field.getName(),field); } return foundFields; } } ); return declaredAccessableFields; }
Example 17
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/configuration/.
Source file: SecurityActions.java

static List<Field> getAccessibleFields(final Class<?> source){ List<Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<List<Field>>(){ public List<Field> run(){ List<Field> foundFields=new ArrayList<Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.add(field); } return foundFields; } } ); return declaredAccessableFields; }
Example 18
From project arquillian-extension-seam2, under directory /src/main/java/org/jboss/arquillian/seam2/configuration/.
Source file: SecurityActions.java

static List<Field> getAccessibleFields(final Class<?> source){ List<Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<List<Field>>(){ public List<Field> run(){ List<Field> foundFields=new ArrayList<Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.add(field); } return foundFields; } } ); return declaredAccessableFields; }
Example 19
From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/server/test/.
Source file: LifecycleTestEnrichmentWatcher.java

private boolean validateIfFieldCanBeSetAndSerialized(Field field){ if (Modifier.isTransient(field.getModifiers()) || (Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers()))) { return false; } return true; }
Example 20
From project arquillian-graphene, under directory /graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/.
Source file: SecurityActions.java

static Map<String,Field> getAccessableFields(final Class<?> source){ Map<String,Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<Map<String,Field>>(){ public Map<String,Field> run(){ Map<String,Field> foundFields=new LinkedHashMap<String,Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.put(field.getName(),field); } return foundFields; } } ); return declaredAccessableFields; }
Example 21
From project arquillian-showcase, under directory /extensions/deploymentscenario/src/main/java/org/jboss/arquillian/showcase/extension/deploymentscenario/.
Source file: ExternalScenarioGenerator.java

private Method getDeploymentMethodFromAnnotation(TestClass testClass){ ReadDeploymentFrom from=testClass.getAnnotation(ReadDeploymentFrom.class); Class<?> deploymentHolderClass=from.value(); String deploymentName=from.named(); for ( Method m : deploymentHolderClass.getMethods()) { if (Modifier.isStatic(m.getModifiers()) && m.isAnnotationPresent(Deployment.class) && m.getAnnotation(Deployment.class).name().equals(deploymentName)) { return m; } } return null; }
Example 22
From project arquillian_deprecated, under directory /extensions/drone/src/main/java/org/jboss/arquillian/drone/configuration/.
Source file: SecurityActions.java

static List<Field> getAccessableFields(final Class<?> source){ List<Field> declaredAccessableFields=AccessController.doPrivileged(new PrivilegedAction<List<Field>>(){ public List<Field> run(){ List<Field> foundFields=new ArrayList<Field>(); for ( Field field : source.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers())) { continue; } if (!field.isAccessible()) { field.setAccessible(true); } foundFields.add(field); } return foundFields; } } ); return declaredAccessableFields; }
Example 23
From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.
Source file: JarClassLoader.java

/** * Invokes main() method on class with provided parameters. * @param sClass class name in form "MyClass" for default packageor "com.abc.MyClass" for class in some package * @param args arguments for the main() method or null. * @throws Throwable wrapper for many exceptions thrown while<p>(1) main() method lookup: ClassNotFoundException, SecurityException, NoSuchMethodException <p>(2) main() method launch: IllegalArgumentException, IllegalAccessException (disabled) <p>(3) Actual cause of InvocationTargetException See {@link http://java.sun.com/developer/Books/javaprogramming/JAR/api/jarclassloader.html}and {@link http://java.sun.com/developer/Books/javaprogramming/JAR/api/example-1dot2/JarClassLoader.java} */ public void invokeMain(String sClass,String[] args) throws Throwable { Class<?> clazz=loadClass(sClass); logInfo(LogArea.CONFIG,"Launch: %s.main(); Loader: %s",sClass,clazz.getClassLoader()); Method method=clazz.getMethod("main",new Class<?>[]{String[].class}); boolean bValidModifiers=false; boolean bValidVoid=false; if (method != null) { method.setAccessible(true); int nModifiers=method.getModifiers(); bValidModifiers=Modifier.isPublic(nModifiers) && Modifier.isStatic(nModifiers); Class<?> clazzRet=method.getReturnType(); bValidVoid=(clazzRet == void.class); } if (method == null || !bValidModifiers || !bValidVoid) { throw new NoSuchMethodException("The main() method in class \"" + sClass + "\" not found."); } try { method.invoke(null,(Object)args); } catch ( InvocationTargetException e) { throw e.getTargetException(); } }
Example 24
From project asterisk-java, under directory /src/main/java/org/asteriskjava/manager/internal/.
Source file: EventBuilderImpl.java

/** * Registers a new event class for the event given by eventType. * @param eventType the name of the event to register the class for. Forexample "Join". * @param clazz the event class to register, must extend{@link ManagerEvent}. * @throws IllegalArgumentException if clazz is not a valid event class. */ public final void registerEventClass(String eventType,Class<? extends ManagerEvent> clazz) throws IllegalArgumentException { Constructor<?> defaultConstructor; if (!ManagerEvent.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(clazz + " is not a ManagerEvent"); } if ((clazz.getModifiers() & Modifier.ABSTRACT) != 0) { throw new IllegalArgumentException(clazz + " is abstract"); } try { defaultConstructor=clazz.getConstructor(new Class[]{Object.class}); } catch ( NoSuchMethodException ex) { throw new IllegalArgumentException(clazz + " has no usable constructor"); } if ((defaultConstructor.getModifiers() & Modifier.PUBLIC) == 0) { throw new IllegalArgumentException(clazz + " has no public default constructor"); } registeredEventClasses.put(eventType.toLowerCase(Locale.US),clazz); logger.debug("Registered event type '" + eventType + "' ("+ clazz+ ")"); }
Example 25
From project astyanax, under directory /src/main/java/com/netflix/astyanax/util/.
Source file: StringUtils.java

public static <T>String joinClassAttributeValues(final T object,String name,Class<T> clazz){ Field[] fields=clazz.getDeclaredFields(); StringBuilder sb=new StringBuilder(); sb.append(name).append("["); sb.append(org.apache.commons.lang.StringUtils.join(Collections2.transform(Collections2.filter(Arrays.asList(fields),new Predicate<Field>(){ @Override public boolean apply( Field field){ if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) return false; return Character.isLowerCase(field.getName().charAt(0)); } } ),new Function<Field,String>(){ @Override public String apply( Field field){ Object value; try { value=field.get(object); } catch ( Exception e) { value="***"; } return field.getName() + "=" + value; } } ),",")); sb.append("]"); return sb.toString(); }
Example 26
/** * Gets all declared fields and all inherited fields. */ protected Set<Field> getFields(Class<?> c){ Set<Field> fields=Sets.newHashSet(c.getDeclaredFields()); while ((c=c.getSuperclass()) != null) { for ( Field f : c.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isPrivate(f.getModifiers())) { fields.add(f); } } } return fields; }
Example 27
/** * Gets all declared fields and all inherited fields. */ protected Set<Field> getFields(Class<?> c){ Set<Field> fields=Sets.newHashSet(c.getDeclaredFields()); while ((c=c.getSuperclass()) != null) { for ( Field f : c.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isPrivate(f.getModifiers())) { fields.add(f); } } } return fields; }
Example 28
From project aunit, under directory /junit/src/main/java/com/toolazydogs/aunit/internal/.
Source file: AnnotatedWithConfiguration.java

/** * {@inheritDoc} */ public Collection<? extends AntlrConfigMethod> getConfigMethods(final TestClass testClass,final Object testInstance){ final List<AntlrConfigMethod> configMethods=new ArrayList<AntlrConfigMethod>(); for ( FrameworkMethod configMethod : testClass.getAnnotatedMethods(Configuration.class)) { final Method method=configMethod.getMethod(); if (!Modifier.isAbstract(method.getModifiers()) && method.getParameterTypes() != null && method.getParameterTypes().length == 0 && method.getReturnType().isArray() && Option.class.isAssignableFrom(method.getReturnType().getComponentType())) { final AppliesTo appliesToAnnotation=configMethod.getAnnotation(AppliesTo.class); if (appliesToAnnotation != null) { configMethods.add(new AppliesToConfigMethod(method,Modifier.isStatic(method.getModifiers()) ? null : testInstance)); } else { configMethods.add(new DefaultConfigMethod(method,Modifier.isStatic(method.getModifiers()) ? null : testInstance)); } } } return configMethods; }
Example 29
From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/reflect/.
Source file: ReflectData.java

private Collection<Field> getFields(Class recordClass){ Map<String,Field> fields=new LinkedHashMap<String,Field>(); Class c=recordClass; do { if (c.getPackage() != null && c.getPackage().getName().startsWith("java.")) break; for ( Field field : c.getDeclaredFields()) if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0) if (fields.put(field.getName(),field) != null) throw new AvroTypeException(c + " contains two fields named: " + field); c=c.getSuperclass(); } while (c != null); return fields.values(); }
Example 30
From project awaitility, under directory /awaitility/src/main/java/com/jayway/awaitility/proxy/.
Source file: ProxyCreator.java

public static Object create(Class<? extends Object> targetClass,InvocationHandler invocationHandler){ Object proxy=null; if (Modifier.isFinal(targetClass.getModifiers())) { if (targetClassHasInterfaces(targetClass)) { proxy=createInterfaceProxy(targetClass,invocationHandler); } else { throw new CannotCreateProxyException(String.format("Cannot create a proxy for class '%s' because it is final and doesn't implement any interfaces.",targetClass.getName())); } } else { proxy=createCGLibProxy(targetClass,invocationHandler); } return proxy; }
Example 31
From project beanvalidation-tck, under directory /tests/src/main/java/org/hibernate/beanvalidation/tck/tests/bootstrap/.
Source file: ValidationProviderTest.java

@Test @SpecAssertion(section="4.4.4.2",id="d") public void testValidationProviderContainsNoArgConstructor(){ ValidationProvider<?> validationProviderUnderTest=TestUtil.getValidationProviderUnderTest(); try { Constructor<?> constructor=validationProviderUnderTest.getClass().getConstructor(); assertTrue(Modifier.isPublic(constructor.getModifiers())); } catch ( Exception e) { fail("The validation provider must have a public no arg constructor"); } }
Example 32
private static MyProperty getMyProperty(Class<? extends Object> valueClass,String propName) throws Exception { MyProperty pd; int index=0; Matcher matcher=INDEXED_PROPERTY.matcher(propName); if (matcher.matches()) { propName=matcher.group(1); index=Integer.parseInt(matcher.group(2)); } try { BeanInfo beanInfo=BeanProperty.getBeanInfo(valueClass); pd=new BeanProperty(BeanProperty.findProperty(beanInfo,propName),index); } catch ( Exception e) { Field declaredField=valueClass.getField(propName); if (declaredField != null && (declaredField.getModifiers() & Modifier.PUBLIC) > 0) { pd=new FieldProperty(declaredField,index); } else { throw e; } } return pd; }
Example 33
From project big-data-plugin, under directory /src/org/pentaho/di/job/entries/hadoopjobexecutor/.
Source file: JarUtility.java

public List<Class<?>> getClassesInJarWithMain(String jarUrl,ClassLoader parentClassloader) throws MalformedURLException { ArrayList<Class<?>> mainClasses=new ArrayList<Class<?>>(); List<Class<?>> allClasses=JarUtility.getClassesInJar(jarUrl,parentClassloader); for ( Class<?> clazz : allClasses) { try { Method mainMethod=clazz.getMethod("main",new Class[]{String[].class}); if (Modifier.isStatic(mainMethod.getModifiers())) { mainClasses.add(clazz); } } catch ( Throwable ignored) { } } return mainClasses; }
Example 34
From project Binaural-Beats, under directory /src/com/ihunda/android/binauralbeat/.
Source file: DefaultProgramsBuilder.java

public static Map<String,ProgramMeta> getProgramMethods(Context context){ if (names != null) return names; names=new HashMap<String,ProgramMeta>(); Class<R.string> resourceStrings=R.string.class; for ( Method method : DefaultProgramsBuilder.class.getMethods()) { if (Modifier.isStatic(method.getModifiers()) && method.getReturnType().isAssignableFrom(Program.class) && method.getName().matches("[A-Z0-9_]+")) { try { Category cat=getMatchingCategory(method.getName()); String parsedMethod=method.getName().toLowerCase().substring(cat.toString().length() + 1); String string_res="program_" + parsedMethod; String nice_name; try { nice_name=context.getString(resourceStrings.getField(string_res).getInt(null)); } catch ( NoSuchFieldException e) { Log.w(TAG,String.format("Missing string for %s",parsedMethod)); nice_name=WordUtils.capitalize(parsedMethod); } ProgramMeta meta=new ProgramMeta(method,nice_name,cat); names.put(nice_name,meta); } catch ( IllegalArgumentException e) { throw new RuntimeException(e); } catch ( IllegalAccessException e) { throw new RuntimeException(e); } } } return names; }
Example 35
From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/util/.
Source file: IntrospectionSupport.java

private static void addFields(Object target,Class startClass,Class stopClass,LinkedHashMap map) throws IllegalArgumentException, IllegalAccessException { if (startClass != stopClass) { IntrospectionSupport.addFields(target,startClass.getSuperclass(),stopClass,map); } Field[] fields=startClass.getDeclaredFields(); for (int i=0; i < fields.length; i++) { Field field=fields[i]; if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || Modifier.isPrivate(field.getModifiers())) { continue; } field.setAccessible(true); Object o=field.get(target); if (o != null && o.getClass().isArray()) { o=Arrays.asList((Object[])o); } map.put(field.getName(),o); } }
Example 36
From project Blitz, under directory /src/com/laxser/blitz/lama/core/.
Source file: GenericUtils.java

protected static void fillConstantFrom(Class<?> clazz,HashMap<String,Object> map){ Field fields[]=clazz.getDeclaredFields(); for ( Field field : fields) { if (field.isSynthetic()) { continue; } int modifiers=field.getModifiers(); if (!Modifier.isStatic(modifiers)) { continue; } try { if (field.isAccessible()) { field.setAccessible(true); } map.put(field.getName(),field.get(null)); } catch ( SecurityException e) { } catch ( IllegalAccessException e) { } } }
Example 37
From project Blueprint, under directory /blueprint-core/src/main/java/org/codemined/blueprint/.
Source file: Deserializer.java

/** * Attempts to deserialize an object using a static factory method. <p> The type is queried for a method that meets the following criteria: <ul> <li>is public and static;</li> <li>has the name {@code methodName};</li> <li>takes one String parameter;</li> <li> {@code type} is assignable from this method's return type, as per {@link Class#isAssignableFrom(Class)}.</li> </ul> If no such method is found, useStaticDeserializer returns null. </p> * @param type Type to deserialize into. * @param methodName Name of the static factory method to use. * @param value String to deserialize from. * @param < T > Type to deserialize into. * @return Deserialized instance or null if no adequate method is found. * @throws BlueprintException if an exception is thrown from inside the deserializer method. */ private <T>T useStaticDeserializer(Class<T> type,String methodName,String value){ Method method; try { method=type.getMethod(methodName,String.class); if (!Modifier.isStatic(method.getModifiers()) || !type.isAssignableFrom(method.getReturnType())) { return null; } } catch ( NoSuchMethodException e) { return null; } try { return type.cast(method.invoke(null,value)); } catch ( Exception e) { throw new BlueprintException("Failed to deserialize configuration item" + " as an instance of " + type.getCanonicalName() + ", using method "+ methodName+ "(String)"+ ", from value \""+ value+ "\"",e); } }
Example 38
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: AggregateConverter.java

private Object createObject(String value,Class type) throws Exception { if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) { throw new Exception("Unable to convert value " + value + " to type "+ type+ ". Type "+ type+ " is an interface or an abstract class"); } Constructor constructor=null; try { constructor=type.getConstructor(String.class); } catch ( NoSuchMethodException e) { throw new RuntimeException("Unable to convert to " + type); } try { return ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(),constructor,value); } catch ( Exception e) { throw new Exception("Unable to convert ",getRealCause(e)); } }
Example 39
/** * Read all relevant icons and returns the Map. The loc should contain the fully qualified URL for the icons. The icon names read will have the words _private, protected, _static, _static_private and _static_protected and the extension ".png" appended. * @param loc root for icon locations * @return Map (can be used directly with getModifiers & 0xf) */ Map<Integer,Image> readIcons(String loc){ Map<Integer,Image> icons=new HashMap<Integer,Image>(); icons.put(Modifier.PUBLIC,readImage(loc,"")); icons.put(Modifier.PRIVATE,readImage(loc,"_private")); icons.put(Modifier.PROTECTED,readImage(loc,"_protected")); icons.put(Modifier.STATIC | Modifier.PUBLIC,readImage(loc,"_static")); icons.put(Modifier.STATIC | Modifier.PRIVATE,readImage(loc,"_static_private")); icons.put(Modifier.STATIC | Modifier.PROTECTED,readImage(loc,"_static_protected")); return icons; }
Example 40
From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.
Source file: TestUtils.java

static void setFinalStatic(Field field,Object newValue) throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true); Field modifiersField=Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field,field.getModifiers() & ~Modifier.FINAL); field.set(null,newValue); }
Example 41
From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.
Source file: HelperManager.java

/** * return a static public method with the given parameter types it exists otherwise null * @param name * @param paramTypes * @return */ private Method lookupLifecycleMethod(Class<?> clazz,String name,Class<?>[] paramTypes){ try { Method m=clazz.getMethod(name,paramTypes); int mod=m.getModifiers(); if (Modifier.isStatic(mod)) { return m; } } catch ( NoSuchMethodException e) { } return null; }
Example 42
From project c3p0, under directory /src/java/com/mchange/v2/c3p0/codegen/.
Source file: BeangenDataSourceGenerator.java

public void generate(ClassInfo info,Class superclassType,Property[] props,Class[] propTypes,IndentedWriter iw) throws IOException { BeangenUtils.writeExplicitDefaultConstructor(Modifier.PRIVATE,info,iw); iw.println(); iw.println("public " + info.getClassName() + "( boolean autoregister )"); iw.println("{"); iw.upIndent(); iw.println("if (autoregister)"); iw.println("{"); iw.upIndent(); iw.println("this.identityToken = C3P0ImplUtils.allocateIdentityToken( this );"); iw.println("C3P0Registry.reregister( this );"); iw.downIndent(); iw.println("}"); iw.downIndent(); iw.println("}"); }
Example 43
From project candlepin, under directory /src/main/java/org/candlepin/util/apicrawl/.
Source file: ApiCrawler.java

private List<RestApiCall> processClass(Class c){ Path a=(Path)c.getAnnotation(Path.class); String parentUrl=a.value(); List<RestApiCall> classApiCalls=new LinkedList<RestApiCall>(); for ( Method m : c.getDeclaredMethods()) { if (Modifier.isPublic(m.getModifiers())) { classApiCalls.add(processMethod(parentUrl,m)); } } return classApiCalls; }
Example 44
From project capedwarf-blue, under directory /bytecode/src/main/java/org/jboss/capedwarf/bytecode/.
Source file: CursorTransformer.java

protected void transform(CtClass clazz) throws Exception { if (isAlreadyModified(clazz)) return; final ClassPool pool=clazz.getClassPool(); CtClass intClass=pool.get(int.class.getName()); CtField indexField=CtField.make("private java.util.concurrent.atomic.AtomicInteger index;",clazz); clazz.addField(indexField); CtConstructor ctor=new CtConstructor(new CtClass[]{pool.get(AtomicInteger.class.getName())},clazz); ctor.setBody("{this.index = $1;}"); clazz.addConstructor(ctor); CtMethod getIndex=new CtMethod(intClass,"getIndex",new CtClass[]{},clazz); getIndex.setModifiers(Modifier.PUBLIC); getIndex.setBody("{return index.get();}"); clazz.addMethod(getIndex); CtConstructor cloneCtor=clazz.getDeclaredConstructor(new CtClass[]{clazz}); cloneCtor.setBody("this($1.index);"); CtMethod writeObject=clazz.getDeclaredMethod("writeObject",new CtClass[]{pool.get(ObjectOutputStream.class.getName())}); writeObject.setBody("$1.writeInt(getIndex());"); CtMethod readObject=clazz.getDeclaredMethod("readObject",new CtClass[]{pool.get(ObjectInputStream.class.getName())}); readObject.setBody("index = new java.util.concurrent.atomic.AtomicInteger($1.readInt()); "); CtMethod advance=clazz.getDeclaredMethod("advance",new CtClass[]{intClass,pool.get(PreparedQuery.class.getName())}); advance.setBody("index.addAndGet($1);"); CtMethod reverse=clazz.getDeclaredMethod("reverse"); reverse.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger((-1) * getIndex()));"); CtMethod toWebSafeString=clazz.getDeclaredMethod("toWebSafeString"); toWebSafeString.setBody("return index.toString();"); CtMethod fromWebSafeString=clazz.getDeclaredMethod("fromWebSafeString",new CtClass[]{pool.get(String.class.getName())}); fromWebSafeString.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger($1 != null && $1.length() > 0 ? Integer.parseInt($1) : 0));"); CtMethod fromByteArray=clazz.getDeclaredMethod("fromByteArray",new CtClass[]{pool.get(byte[].class.getName())}); fromByteArray.setBody("return fromWebSafeString(new String($1));"); CtMethod equals=clazz.getDeclaredMethod("equals",new CtClass[]{pool.get(Object.class.getName())}); equals.setBody("return ($1 instanceof com.google.appengine.api.datastore.Cursor) && ((com.google.appengine.api.datastore.Cursor) $1).getIndex() == getIndex();"); CtMethod hashCode=clazz.getDeclaredMethod("hashCode"); hashCode.setBody("return getIndex();"); CtMethod toString=clazz.getDeclaredMethod("toString"); toString.setBody("return \"Cursor:\" + index;"); }
Example 45
From project cdk, under directory /commons/src/test/java/org/richfaces/cdk/.
Source file: CdkTestRunner.java

/** * Gets all declared fields and all inherited fields. */ protected Set<Field> getFields(Class<?> c){ Set<Field> fields=new HashSet<Field>(Arrays.asList(c.getDeclaredFields())); while ((c=c.getSuperclass()) != null) { for ( Field f : c.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isPrivate(f.getModifiers())) { fields.add(f); } } } return fields; }
Example 46
From project ceres, under directory /ceres-binding/src/main/java/com/bc/ceres/binding/.
Source file: PropertyContainer.java

private static void collectProperties(PropertyContainer container,Class<?> fieldProvider,PropertyDescriptorFactory descriptorFactory,PropertyAccessorFactory accessorFactory){ if (!fieldProvider.equals(Object.class)) { collectProperties(container,fieldProvider.getSuperclass(),descriptorFactory,accessorFactory); Field[] declaredFields=fieldProvider.getDeclaredFields(); for ( Field field : declaredFields) { final int mod=field.getModifiers(); if (!Modifier.isTransient(mod) && !Modifier.isStatic(mod)) { final PropertyDescriptor descriptor=PropertyDescriptor.createPropertyDescriptor(field,descriptorFactory); if (descriptor != null) { final PropertyAccessor accessor=accessorFactory.createValueAccessor(field); if (accessor != null) { container.addProperty(new Property(descriptor,accessor)); } } } } } }
Example 47
private void addOccupant(T occupant){ Class cl=occupant.getClass(); do { if ((cl.getModifiers() & Modifier.ABSTRACT) == 0) occupantClasses.add(cl); cl=cl.getSuperclass(); } while (cl != Object.class); }
Example 48
From project chromattic, under directory /cglib/src/main/java/org/chromattic/cglib/.
Source file: MethodInterceptorInvoker.java

public Object intercept(Object o,Method method,Object[] args,MethodProxy methodProxy) throws Throwable { if (Modifier.isAbstract(method.getModifiers())) { return invoker.invoke(o,method,args); } else { return methodProxy.invokeSuper(o,args); } }
Example 49
From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/admin/util/.
Source file: JSONObject.java

private void populateMap(Object bean){ Class klass=bean.getClass(); boolean includeSuperClass=klass.getClassLoader() != null; Method[] methods=includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i=0; i < methods.length; i+=1) { try { Method method=methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name=method.getName(); String key=""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key=""; } else { key=name.substring(3); } } else if (name.startsWith("is")) { key=name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key=key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key=key.substring(0,1).toLowerCase() + key.substring(1); } Object result=method.invoke(bean,(Object[])null); if (result != null) { this.map.put(key,wrap(result)); } } } } catch ( Exception ignore) { } } }
Example 50
From project cipango, under directory /cipango-annotations/src/main/java/org/cipango/annotations/.
Source file: ResourceAnnotationHandler.java

@Override @SuppressWarnings("rawtypes") public void handleField(Class clazz,Field field){ Resource resource=(Resource)field.getAnnotation(Resource.class); if (resource != null) { String jndiName=getSipResourceJndiName(field); if (jndiName != null) { if (Modifier.isStatic(field.getModifiers())) { LOG.warn("Skipping Resource annotation on " + clazz.getName() + "."+ field.getName()+ ": cannot be static"); return; } if (Modifier.isFinal(field.getModifiers())) { LOG.warn("Skipping Resource annotation on " + clazz.getName() + "."+ field.getName()+ ": cannot be final"); return; } InjectionCollection injections=(InjectionCollection)_context.getAttribute(InjectionCollection.INJECTION_COLLECTION); if (injections == null) { injections=new InjectionCollection(); _context.setAttribute(InjectionCollection.INJECTION_COLLECTION,injections); } Injection injection=new Injection(); injection.setTarget(clazz,field,field.getType()); injection.setJndiName(jndiName); injections.add(injection); } } else super.handleField(clazz,field); }
Example 51
public InstanceMethodExpr(String source,int line,int column,Symbol tag,Expr target,String methodName,IPersistentVector args){ this.source=source; this.line=line; this.column=column; this.args=args; this.methodName=methodName; this.target=target; this.tag=tag; if (target.hasJavaClass() && target.getJavaClass() != null) { List methods=Reflector.getMethods(target.getJavaClass(),args.count(),methodName,false); if (methods.isEmpty()) method=null; else { int methodidx=0; if (methods.size() > 1) { ArrayList<Class[]> params=new ArrayList(); ArrayList<Class> rets=new ArrayList(); for (int i=0; i < methods.size(); i++) { java.lang.reflect.Method m=(java.lang.reflect.Method)methods.get(i); params.add(m.getParameterTypes()); rets.add(m.getReturnType()); } methodidx=getMatchingParams(methodName,params,args,rets); } java.lang.reflect.Method m=(java.lang.reflect.Method)(methodidx >= 0 ? methods.get(methodidx) : null); if (m != null && !Modifier.isPublic(m.getDeclaringClass().getModifiers())) { m=Reflector.getAsMethodOfPublicBase(m.getDeclaringClass(),m); } method=m; } } else method=null; if (method == null && RT.booleanCast(RT.WARN_ON_REFLECTION.deref())) { RT.errPrintWriter().format("Reflection warning, %s:%d:%d - call to %s can't be resolved.\n",SOURCE_PATH.deref(),line,column,methodName); } }
Example 52
From project closure-templates, under directory /java/tests/com/google/template/soy/parsepasses/contextautoesc/.
Source file: EscapingModeTest.java

private static Method getSoyUtilsMethodForEscapingMode(EscapingMode mode){ Method method=SOY_UTILS_METHODS.get(mode); String methodName="$$" + mode.directiveName.substring(1); try { method=SoyUtils.class.getDeclaredMethod(methodName,SoyData.class); } catch ( NoSuchMethodException exStr) { throw new AssertionFailedError("No handler in SoyUtils for " + mode + " : "+ methodName); } assertEquals("return type of " + methodName,String.class,method.getReturnType()); assertTrue(methodName + " not static",Modifier.isStatic(method.getModifiers())); assertTrue(methodName + " not public",Modifier.isPublic(method.getModifiers())); SOY_UTILS_METHODS.put(mode,method); return method; }
Example 53
From project cloudify, under directory /restful/src/main/java/org/cloudifysource/rest/out/.
Source file: OutputUtils.java

public static boolean isValidObjectGetter(Method method){ String methodName=method.getName(); Class<?> retType=method.getReturnType(); if (methodName.equals("getGigaSpace") || methodName.equals("getIJSpace")) { return false; } if (methodName.equals("getRegistrar")) { return false; } if (method.getModifiers() == Modifier.PRIVATE) { return false; } if (methodName.equals("getClass")) { return false; } if (methodName.endsWith("Changed") || methodName.endsWith("Removed") || methodName.endsWith("Added")) { return false; } if (retType.getCanonicalName().contains(".events")) { return false; } if (method.getParameterTypes().length > 0) { return false; } if (AdminTypeBlacklist.in(retType)) { return false; } if (methodName.startsWith("is") && (retType.equals(boolean.class) || retType.equals(Boolean.class))) { return true; } else if (!methodName.startsWith("get")) { return false; } return true; }
Example 54
From project codjo-segmentation, under directory /codjo-segmentation-server/src/test/java/net/codjo/segmentation/server/preference/family/.
Source file: DefaultFunctionHolderTest.java

public void test_allFunctionDeclared(){ Map map=new HashMap(); List all=defaultFunctionHolder.getAllFunctions(); for (Iterator iter=all.iterator(); iter.hasNext(); ) { String func=(String)iter.next(); int idx=func.indexOf("("); map.put(func.substring(defaultFunctionHolder.getName().length() + 1,idx),func); } map.put("getAllFunctions",""); map.put("getName",""); Method[] method=defaultFunctionHolder.getClass().getDeclaredMethods(); for (int i=0; i < method.length; i++) { if (method[i].getModifiers() == Modifier.PUBLIC) { if (!map.containsKey(method[i].getName())) { fail("La methode " + method[i].getName() + " n'est pas declar? dans la methode getAllFunctions"); } else { map.remove(method[i].getName()); } } } assertEquals("Toutes les methodes de getAllFunctions existent",0,map.size()); }
Example 55
From project codjo-standalone-common, under directory /src/main/java/net/codjo/persistent/sql/.
Source file: SimpleHomeFactory.java

/** * Retourne le premier constructeur public definie sur la classe <code>c </code> * @param c La classe de recherche * @return Le premier constructeur public * @exception NoSuchMethodException Si aucun constructeur public */ protected Constructor findConstructor(Class c) throws NoSuchMethodException { Constructor[] classConstructors=c.getDeclaredConstructors(); for (int i=0; i < classConstructors.length; i++) { if (classConstructors[i].getModifiers() == Modifier.PUBLIC) { debug("Constructeur : " + classConstructors[i]); return classConstructors[i]; } } throw new NoSuchMethodException("Aucun constructeur public : " + c); }
Example 56
From project collections-generic, under directory /src/test/org/apache/commons/collections15/.
Source file: BulkTest.java

/** * Returns a {@link TestSuite} for testing all of the simple tests<I>and</I> all the bulk tests defined by the given class.<P> <p/> The class is examined for simple and bulk test methods; any child bulk tests are also examined recursively; and the results are stored in a hierarchal {@link TestSuite}.<P> <p/> The given class must be a subclass of <code>BulkTest</code> and must not be abstract.<P> * @param c the class to examine for simple and bulk tests * @return a {@link TestSuite} containing all the simple and bulk testsdefined by that class */ public static TestSuite makeSuite(Class c){ if (Modifier.isAbstract(c.getModifiers())) { throw new IllegalArgumentException("Class must not be abstract."); } if (!BulkTest.class.isAssignableFrom(c)) { throw new IllegalArgumentException("Class must extend BulkTest."); } return new BulkTestSuiteMaker(c).make(); }
Example 57
From project cometd, under directory /cometd-java/cometd-java-annotations/src/main/java/org/cometd/annotation/.
Source file: AnnotationProcessor.java

protected boolean processPostConstruct(Object bean){ if (bean == null) return false; List<Method> postConstructs=new ArrayList<>(); for (Class<?> c=bean.getClass(); c != null; c=c.getSuperclass()) { boolean foundInClass=false; Method[] methods=c.getDeclaredMethods(); for ( Method method : methods) { PostConstruct postConstruct=method.getAnnotation(PostConstruct.class); if (postConstruct != null) { if (foundInClass) throw new RuntimeException("Invalid @PostConstruct method " + method + ": another method with the same annotation exists"); foundInClass=true; if (method.getReturnType() != Void.TYPE) throw new RuntimeException("Invalid @PostConstruct method " + method + ": it must have void return type"); if (method.getParameterTypes().length > 0) throw new RuntimeException("Invalid @PostConstruct method " + method + ": it must have no parameters"); if (Modifier.isStatic(method.getModifiers())) throw new RuntimeException("Invalid @PostConstruct method " + method + ": it must not be static"); postConstructs.add(method); } } } Collections.reverse(postConstructs); boolean result=false; for ( Method method : postConstructs) { invokeMethod(bean,method); result=true; } return result; }
Example 58
/** * ????????? * @param o */ static void setAccessibleWorkaround(AccessibleObject o){ if (o == null || o.isAccessible()) { return; } Member m=(Member)o; if (Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); } catch ( SecurityException e) { } } }
Example 59
From project components, under directory /bean/src/test/java/org/switchyard/component/bean/config/model/.
Source file: BeanSwitchYardScannerTest.java

private void checkBeanModel(BeanComponentImplementationModel model) throws ClassNotFoundException { Class<?> serviceClass=Classes.forName(model.getClazz(),getClass()); Assert.assertFalse(serviceClass.isInterface()); Assert.assertFalse(Modifier.isAbstract(serviceClass.getModifiers())); if (!serviceClass.isAnnotationPresent(Service.class)) { boolean referencePresent=false; for ( Field f : serviceClass.getDeclaredFields()) { if (f.isAnnotationPresent(Reference.class)) { referencePresent=true; break; } } Assert.assertTrue("Bean classes without an @Service must have at least one @Reference",referencePresent); } }
Example 60
From project core_1, under directory /api/src/main/java/org/switchyard/metadata/java/.
Source file: JavaService.java

/** * Creates a ServiceInterface from the specified Java class or interface. This is the equivalent of <code>fromClass(serviceInterface, null)</code>. * @param serviceInterface class or interface representing the service interface * @return ServiceInterface representing the Java class */ public static JavaService fromClass(Class<?> serviceInterface){ HashSet<ServiceOperation> ops=new HashSet<ServiceOperation>(); for ( Method m : serviceInterface.getDeclaredMethods()) { if (Modifier.isPublic(m.getModifiers())) { Class<?>[] params=m.getParameterTypes(); if (params.length > 1) { throw new RuntimeException("Service operations on a Java interface must have exactly one parameter."); } OperationTypeQNames operationTypeNames=new OperationTypeQNames(m); if (m.getReturnType().equals(Void.TYPE)) { ops.add(new InOnlyOperation(m.getName(),operationTypeNames.in())); } else { ops.add(new InOutOperation(m.getName(),operationTypeNames.in(),operationTypeNames.out(),operationTypeNames.fault())); } } } return new JavaService(ops,serviceInterface); }
Example 61
From project core_4, under directory /impl/src/main/java/org/richfaces/application/.
Source file: DependencyInjectionServiceImpl.java

private void verifyPostConstructMethod(Method method){ if (method.getParameterTypes().length != 0) { throw new IllegalStateException(MessageFormat.format("Post-construction method {0} has one or more parameters",method.toString())); } if (!Void.TYPE.equals(method.getReturnType())) { throw new IllegalStateException(MessageFormat.format("Post-construction method {0} has incorrect return type",method.toString())); } if ((method.getModifiers() & Modifier.STATIC) != 0) { throw new IllegalStateException(MessageFormat.format("Post-construction method {0} is static",method.toString())); } Class<?>[] exceptionTypes=method.getExceptionTypes(); for ( Class<?> exceptionType : exceptionTypes) { if (isUncheckedException(exceptionType)) { continue; } throw new IllegalStateException(MessageFormat.format("Post-construction method {0} throws checked exception",method.toString())); } }
Example 62
From project cp-common-utils, under directory /src/com/clarkparsia/common/util/.
Source file: ClassPath.java

/** * Return all the classes which implement/extend the given class and are instantiable (ie not abstract, not interfaces themselves) * @param theClass the parent class/interface * @return all matching classes */ public static Collection<Class> instantiableClasses(Class<?> theClass){ return Collections2.filter(classes(theClass),new Predicate<Class>(){ public boolean apply( final Class theClass){ return !theClass.isInterface() && !Modifier.isAbstract(theClass.getModifiers()); } } ); }
Example 63
public SignPatch(hr old){ super(nullId(),lv.class,false); this.old=old; for ( Field f : FIELDS) try { if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) continue; f.setAccessible(true); Object o=f.get(old); f.setAccessible(true); f.set(this,o); } catch ( Exception e) { System.out.println("Failed to copy field: " + f.getName()); e.printStackTrace(); } }
Example 64
From project crunch, under directory /scrunch/src/main/java/org/apache/scrunch/.
Source file: ScalaSafeReflectData.java

private Collection<Field> getFields(Class recordClass){ Map<String,Field> fields=new LinkedHashMap<String,Field>(); Class c=recordClass; do { if (c.getPackage() != null && c.getPackage().getName().startsWith("java.")) break; for ( Field field : c.getDeclaredFields()) if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0) if (fields.put(field.getName(),field) != null) throw new AvroTypeException(c + " contains two fields named: " + field); c=c.getSuperclass(); } while (c != null); return fields.values(); }
Example 65
From project Cyborg, under directory /src/main/java/com/alta189/cyborg/api/command/annotation/.
Source file: AnnotatedCommandFactory.java

public List<com.alta189.cyborg.api.command.Command> createCommands(Named owner,Class<?> clazz){ List<com.alta189.cyborg.api.command.Command> result=new ArrayList<com.alta189.cyborg.api.command.Command>(); Object instance=null; if (injector != null) { instance=injector.newInstance(clazz); } for ( Method method : clazz.getMethods()) { if (!Modifier.isStatic(method.getModifiers()) && instance == null) { continue; } if (!method.isAnnotationPresent(Command.class)) { continue; } Command command=method.getAnnotation(Command.class); if (command.name() == null) { continue; } if (!method.getReturnType().equals(CommandResult.class)) { continue; } com.alta189.cyborg.api.command.Command cmd=new com.alta189.cyborg.api.command.Command(owner,command.name()); cmd.getAliases().addAll(Arrays.asList(command.aliases())); cmd.setDesc(command.desc()); cmd.setExecutor(new AnnotatedCommandExecutor(instance,method)); if (method.isAnnotationPresent(Usage.class)) { Usage usage=method.getAnnotation(Usage.class); cmd.setUsage(usage.value()); } if (method.isAnnotationPresent(Hidden.class)) { Hidden hidden=method.getAnnotation(Hidden.class); cmd.setHiddenFromList(hidden.value()); } result.add(cmd); } return result; }
Example 66
From project daleq, under directory /daleq-core/src/main/java/de/brands4friends/daleq/core/internal/types/.
Source file: FieldScanner.java

@Override public boolean apply(@Nullable final Field field){ if (field == null) { return false; } final int modifiers=field.getModifiers(); return Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) && Modifier.isPublic(modifiers); }
Example 67
From project deadbolt, under directory /app/controllers/deadbolt/reports/.
Source file: DeadboltReporter.java

private static ControllerReport getControllerReport(Class controller){ ControllerReport controllerReport=new ControllerReport(controller.getCanonicalName()); Method[] methods=controller.getMethods(); for ( Method method : methods) { if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().equals(Controller.class)) { MethodReport methodReport=getMethodReport(method); controllerReport.addMethodReport(methodReport); } } return controllerReport; }
Example 68
From project DeuceSTM, under directory /src/java/org/deuce/reflection/.
Source file: AddressUtil.java

/** * Fetches the field direct address. * @param field field reference * @return direct address */ public static long getAddress(Field field){ if (Modifier.isStatic(field.getModifiers())) { return UnsafeHolder.getUnsafe().staticFieldOffset(field); } else { return UnsafeHolder.getUnsafe().objectFieldOffset(field); } }
Example 69
From project droolsjbpm-integration, under directory /drools-camel/src/main/java/org/drools/camel/component/.
Source file: FastCloner.java

/** * registers all static fields of these classes. Those static fields won't be cloned when an instance of the class is cloned. This is useful i.e. when a static field object is added into maps or sets. At that point, there is no way for the cloner to know that it was static except if it is registered. * @param classes array of classes */ public void registerStaticFields(final Class<?>... classes){ for ( final Class<?> c : classes) { final List<Field> fields=allFields(c); for ( final Field field : fields) { final int mods=field.getModifiers(); if (Modifier.isStatic(mods) && !field.getType().isPrimitive()) { registerConstant(c,field.getName()); } } } }
Example 70
From project dynalink, under directory /src/main/java/org/dynalang/dynalink/beans/.
Source file: AbstractJavaLinker.java

private static Method getMostGenericGetter(String name,Class<?> returnType,Class<?> declaringClass){ if (declaringClass == null) { return null; } for ( Class<?> itf : declaringClass.getInterfaces()) { final Method itfGetter=getMostGenericGetter(name,returnType,itf); if (itfGetter != null) { return itfGetter; } } final Method superGetter=getMostGenericGetter(name,returnType,declaringClass.getSuperclass()); if (superGetter != null) { return superGetter; } if (Modifier.isPublic(declaringClass.getModifiers())) { try { return declaringClass.getMethod(name); } catch ( NoSuchMethodException e) { } } return null; }
Example 71
From project EasySOA, under directory /samples/Talend-Airport-Service/SimpleProvider_0.1/SimpleProvider/src/routines/system/.
Source file: JSONObject.java

private void populateMap(Object bean){ Class klass=bean.getClass(); boolean includeSuperClass=klass.getClassLoader() != null; Method[] methods=(includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); for (int i=0; i < methods.length; i+=1) { try { Method method=methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name=method.getName(); String key=""; if (name.startsWith("get")) { if (name.equals("getClass") || name.equals("getDeclaringClass")) { key=""; } else { key=name.substring(3); } } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key=key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key=key.substring(0,1).toLowerCase() + key.substring(1); } Object result=method.invoke(bean,(Object[])null); map.put(key,wrap(result)); } } } catch ( Exception ignore) { } } }
Example 72
From project echo3, under directory /src/server-java/app/nextapp/echo/app/reflect/.
Source file: ObjectIntrospector.java

/** * Returns the name of the type that defines the specified property. * @param propertyName the name of the property * @return the defining class */ public String getPropertyDefinitionConcreteType(String propertyName){ PropertyDescriptor propertyDescriptor=getPropertyDescriptor(propertyName); if (propertyDescriptor == null) { return null; } else { Method readMethod; if (propertyDescriptor instanceof IndexedPropertyDescriptor) { readMethod=((IndexedPropertyDescriptor)propertyDescriptor).getIndexedReadMethod(); } else { readMethod=propertyDescriptor.getReadMethod(); } if (readMethod == null) { return null; } else { Class definitionClass=readMethod.getDeclaringClass(); while ((definitionClass.getModifiers() & Modifier.ABSTRACT) != 0) { definitionClass=definitionClass.getSuperclass(); } return definitionClass.getName(); } } }
Example 73
From project eclipse.platform.runtime, under directory /bundles/org.eclipse.e4.core.di/src/org/eclipse/e4/core/internal/di/.
Source file: InjectorImpl.java

/** * Make the processor visit all declared fields on the given class. */ private boolean processFields(Object userObject,PrimaryObjectSupplier objectSupplier,PrimaryObjectSupplier tempSupplier,Class<?> objectsClass,boolean track,List<Requestor> requestors){ boolean injectedStatic=false; Field[] fields=objectsClass.getDeclaredFields(); for (int i=0; i < fields.length; i++) { Field field=fields[i]; if (Modifier.isStatic(field.getModifiers())) { if (hasInjectedStatic(objectsClass)) continue; injectedStatic=true; } if (!field.isAnnotationPresent(Inject.class)) continue; requestors.add(new FieldRequestor(field,this,objectSupplier,tempSupplier,userObject,track)); } return injectedStatic; }
Example 74
From project elasticsearch-osem, under directory /src/main/java/org/elasticsearch/osem/common/springframework/util/.
Source file: ClassUtils.java

/** * Determine whether the given method is overridable in the given target class. * @param method the method to check * @param targetClass the target class to check against */ private static boolean isOverridable(Method method,Class targetClass){ if (Modifier.isPrivate(method.getModifiers())) { return false; } if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) { return true; } return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)); }
Example 75
From project elw, under directory /datapath/src/test/java/elw/dp/mips/.
Source file: AluTest.java

public void testAnnotations(){ final Method[] aluMethods=Alu.class.getDeclaredMethods(); for ( Method m : aluMethods) { if (Modifier.isStatic(m.getModifiers())) { continue; } final InstructionDesc descAnnot=m.getAnnotation(InstructionDesc.class); assertNotNull(m.getName(),descAnnot); assertEquals(m.getName(),32,descAnnot.template().length()); assertTrue(m.getName(),descAnnot.syntax().startsWith(m.getName())); } }
Example 76
From project Empire, under directory /core/src/com/clarkparsia/empire/annotation/.
Source file: RdfGenerator.java

@SuppressWarnings("unchecked") private static <T>Class<T> determineClass(Class<T> theOrigClass,T theObj,DataSource theSource) throws InvalidRdfException, DataSourceException { Class aResult=theOrigClass; final SupportsRdfId aTmpSupportsRdfId=asSupportsRdfId(theObj); final Collection<Value> aTypes=DataSourceUtil.getValues(theSource,EmpireUtil.asResource(EmpireUtil.asSupportsRdfId(theObj)),RDF.TYPE); for ( Value aValue : aTypes) { if (!(aValue instanceof URI)) { continue; } URI aType=(URI)aValue; for ( Class aCandidateClass : TYPE_TO_CLASS.get(aType)) { if (aCandidateClass.equals(aResult)) { continue; } if (aResult.isAssignableFrom(aCandidateClass)) { aResult=aCandidateClass; } } } try { if (aResult.isInterface() || Modifier.isAbstract(aResult.getModifiers()) || !EmpireGenerated.class.isAssignableFrom(aResult)) { aResult=com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(aResult); } } catch ( Exception e) { throw new InvalidRdfException("Cannot generate a class for a bean",e); } return aResult; }
Example 77
From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/editor/.
Source file: PropertyCollection.java

/** * @param data the data to set */ public void setData(Object data){ this.data=data; this.fields.clear(); this.fieldNames.clear(); if (data != null) { Field[] f=data.getClass().getDeclaredFields(); for (int i=0; i < f.length; i++) { if ((f[i].getModifiers() & Modifier.FINAL) == 0) { Class c=f[i].getType(); if (isDirectEditableType(c)) { f[i].setAccessible(true); this.fields.add(f[i]); this.fieldNames.add(f[i].getName()); } } } } this.model.updateListeners(); }
Example 78
public void registerMethod(Method method){ Args a; Class<?>[] pt=method.getParameterTypes(); if (!Modifier.isStatic(method.getModifiers())) { Class[] all=new Class[pt.length + 1]; all[0]=method.getDeclaringClass(); System.arraycopy(pt,0,all,1,pt.length); a=new Args(all); } else { a=new Args(pt); } found.put(a,new BuiltInFunction(method)); }
Example 79
From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/query/.
Source file: DefaultQueryBinding.java

private Map<String,String> buildFieldMap(final Class targetType){ Map<String,String> fieldMap=new HashMap<String,String>(); Field[] fields=targetType.getDeclaredFields(); for ( Field f : fields) if (Modifier.isStatic(f.getModifiers())) continue; else if (f.isAnnotationPresent(HttpParameterMapping.class)) { fieldMap.put(f.getAnnotation(HttpParameterMapping.class).parameter(),f.getName()); fieldMap.put(f.getName().substring(0,1).toUpperCase().concat(f.getName().substring(1)),f.getName()); } else fieldMap.put(f.getName().substring(0,1).toUpperCase().concat(f.getName().substring(1)),f.getName()); return fieldMap; }
Example 80
From project ExperienceMod, under directory /ExperienceMod/src/com/comphenix/xp/reflect/.
Source file: FieldUtils.java

/** * Gets an accessible <code>Field</code> by name breaking scope if requested. Superclasses/interfaces will be considered. * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the<code>setAccessible</code> method. <code>False</code> will only match public fields. * @return the Field object * @throws IllegalArgumentException if the class or field name is null */ public static Field getField(final Class cls,String fieldName,boolean forceAccess){ if (cls == null) { throw new IllegalArgumentException("The class must not be null"); } if (fieldName == null) { throw new IllegalArgumentException("The field name must not be null"); } for (Class acls=cls; acls != null; acls=acls.getSuperclass()) { try { Field field=acls.getDeclaredField(fieldName); if (!Modifier.isPublic(field.getModifiers())) { if (forceAccess) { field.setAccessible(true); } else { continue; } } return field; } catch ( NoSuchFieldException ex) { } } Field match=null; for (Iterator intf=ClassUtils.getAllInterfaces(cls).iterator(); intf.hasNext(); ) { try { Field test=((Class)intf.next()).getField(fieldName); if (match != null) { throw new IllegalArgumentException("Reference to field " + fieldName + " is ambiguous relative to "+ cls+ "; a matching field exists on two or more implemented interfaces."); } match=test; } catch ( NoSuchFieldException ex) { } } return match; }
Example 81
From project fakereplace, under directory /core/src/main/java/org/fakereplace/reflection/.
Source file: ConstructorReflection.java

@SuppressWarnings("restriction") public static Object newInstance(Constructor<?> method,Object... args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException { final MethodData data=ClassDataStore.instance().getMethodInformation(method.getDeclaringClass().getName()); final Class<?> info=ClassDataStore.instance().getRealClassFromProxyName(method.getDeclaringClass().getName()); try { final Constructor<?> invoke=info.getConstructor(int.class,Object[].class,ConstructorArgument.class); Object ar=args; if (ar == null) { ar=new Object[0]; } if (!Modifier.isPublic(method.getModifiers()) && !method.isAccessible()) { Class<?> caller=sun.reflect.Reflection.getCallerClass(2); Reflection.ensureMemberAccess(caller,method.getDeclaringClass(),null,method.getModifiers()); } return invoke.newInstance(data.getMethodNo(),ar,null); } catch ( NoSuchMethodException e) { throw new RuntimeException(e); } catch ( SecurityException e) { throw new RuntimeException(e); } }
Example 82
From project fastjson, under directory /src/main/java/com/alibaba/fastjson/parser/.
Source file: ParserConfig.java

public FieldDeserializer createFieldDeserializer(ParserConfig mapping,Class<?> clazz,FieldInfo fieldInfo){ boolean asmEnable=this.asmEnable; if (!Modifier.isPublic(clazz.getModifiers())) { asmEnable=false; } if (fieldInfo.getFieldClass() == Class.class) { asmEnable=false; } if (ASMClassLoader.isExternalClass(clazz)) { asmEnable=false; } if (!asmEnable) { return createFieldDeserializerWithoutASM(mapping,clazz,fieldInfo); } try { return ASMDeserializerFactory.getInstance().createFieldDeserializer(mapping,clazz,fieldInfo); } catch ( Throwable e) { e.printStackTrace(); } return createFieldDeserializerWithoutASM(mapping,clazz,fieldInfo); }
Example 83
From project flatpack-java, under directory /core/src/main/java/com/getperka/flatpack/ext/.
Source file: TypeContext.java

/** * Returns {@code true} for:<ul> <li>public Foo getFoo()</li> <li>public boolean isFoo()</li> <li> {@code @PermitAll} <any modifier> Foo getFoo()</li><li> {@code @RolesAllowed} <any modifier> Foo getFoo()</li></ul> Ignores any method declared annotated with {@link Transient} unless {@link PermitAll} or{@link RolesAllowed} is present. */ private static boolean isGetter(Method m){ if (m.getParameterTypes().length != 0) { return false; } String name=m.getName(); if (name.startsWith("get") && name.length() > 3 || name.startsWith("is") && name.length() > 2 && isBoolean(m.getReturnType())) { if (m.isAnnotationPresent(PermitAll.class)) { return true; } if (m.isAnnotationPresent(RolesAllowed.class)) { return true; } if (hasAnnotationWithSimpleName(m,"Transient")) { return false; } if (Modifier.isPublic(m.getModifiers())) { return true; } } return false; }