List of usage examples for java.lang.reflect Modifier isPublic
public static boolean isPublic(int mod)
From source file:org.apache.click.service.XmlConfigService.java
/** * Return the fields annotated with the Bindable annotation. * * @param pageClass the page class//from w w w . j a v a2s .c om * @return the map of bindable fields */ private static Map getAnnotatedBindableFields(Class pageClass) { List<Class> pageClassList = new ArrayList<Class>(); pageClassList.add(pageClass); Class parentClass = pageClass.getSuperclass(); while (parentClass != null) { // Include parent classes up to but excluding Page.class if (parentClass.isAssignableFrom(Page.class)) { break; } pageClassList.add(parentClass); parentClass = parentClass.getSuperclass(); } // Reverse class list so parents are processed first, with the // actual page class fields processed last. This will enable the // page classes fields to override parent class fields Collections.reverse(pageClassList); Map<String, Field> fieldMap = new TreeMap<String, Field>(); for (Class aPageClass : pageClassList) { for (Field field : aPageClass.getDeclaredFields()) { if (field.getAnnotation(Bindable.class) != null) { fieldMap.put(field.getName(), field); // If field is not public set accessibility true if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } } } } return fieldMap; }
From source file:org.evosuite.testcase.TestCodeVisitor.java
private Class<?> getExceptionClassToUse(Throwable exception) { /*/*from w ww . j av a2 s .c o m*/ we can only catch a public class. for "readability" of tests, it shouldn't be a mock one either */ Class<?> ex = exception.getClass(); while (!Modifier.isPublic(ex.getModifiers()) || EvoSuiteMock.class.isAssignableFrom(ex) || ex.getCanonicalName().startsWith("com.sun.")) { ex = ex.getSuperclass(); } return ex; }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
/** * Checks if the given field is a valid pojo field: * - it is public//from w ww .j av a2 s .c om * OR * - there are getter and setter methods for the field. * * @param f field to check * @param clazz class of field * @param typeHierarchy type hierarchy for materializing generic types */ private boolean isValidPojoField(Field f, Class<?> clazz, ArrayList<Type> typeHierarchy) { if (Modifier.isPublic(f.getModifiers())) { return true; } else { boolean hasGetter = false, hasSetter = false; final String fieldNameLow = f.getName().toLowerCase().replaceAll("_", ""); Type fieldType = f.getGenericType(); Class<?> fieldTypeWrapper = ClassUtils.primitiveToWrapper(f.getType()); TypeVariable<?> fieldTypeGeneric = null; if (fieldType instanceof TypeVariable) { fieldTypeGeneric = (TypeVariable<?>) fieldType; fieldType = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) fieldType); } for (Method m : clazz.getMethods()) { final String methodNameLow = m.getName().endsWith("_$eq") ? m.getName().toLowerCase().replaceAll("_", "").replaceFirst("\\$eq$", "_\\$eq") : m.getName().toLowerCase().replaceAll("_", ""); // check for getter if ( // The name should be "get<FieldName>" or "<fieldName>" (for scala) or "is<fieldName>" for boolean fields. (methodNameLow.equals("get" + fieldNameLow) || methodNameLow.equals("is" + fieldNameLow) || methodNameLow.equals(fieldNameLow)) && // no arguments for the getter m.getParameterTypes().length == 0 && // return type is same as field type (or the generic variant of it) (m.getGenericReturnType().equals(fieldType) || (fieldTypeWrapper != null && m.getReturnType().equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericReturnType().equals(fieldTypeGeneric)))) { if (hasGetter) { throw new IllegalStateException("Detected more than one getter"); } hasGetter = true; } // check for setters (<FieldName>_$eq for scala) if ((methodNameLow.equals("set" + fieldNameLow) || methodNameLow.equals(fieldNameLow + "_$eq")) && m.getParameterTypes().length == 1 && // one parameter of the field's type (m.getGenericParameterTypes()[0].equals(fieldType) || (fieldTypeWrapper != null && m.getParameterTypes()[0].equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericParameterTypes()[0].equals(fieldTypeGeneric))) && // return type is void. m.getReturnType().equals(Void.TYPE)) { if (hasSetter) { throw new IllegalStateException("Detected more than one setter"); } hasSetter = true; } } if (hasGetter && hasSetter) { return true; } else { if (!hasGetter) { LOG.debug(clazz + " does not contain a getter for field " + f.getName()); } if (!hasSetter) { LOG.debug(clazz + " does not contain a setter for field " + f.getName()); } return false; } } }
From source file:org.apache.openjpa.enhance.PCEnhancer.java
/** * Adds the <code>pcCopyKeyFieldsToObjectId</code> methods * to classes using application identity. *///from w w w . j a va2 s. c o m private void addCopyKeyFieldsToObjectIdMethod(boolean fieldManager) throws NoSuchMethodException { // public void pcCopyKeyFieldsToObjectId (ObjectIdFieldSupplier fs, // Object oid) String[] args = (fieldManager) ? new String[] { OIDFSTYPE.getName(), Object.class.getName() } : new String[] { Object.class.getName() }; BCMethod method = _pc.declareMethod(PRE + "CopyKeyFieldsToObjectId", void.class.getName(), args); Code code = method.getCode(true); // single field identity always throws exception if (_meta.isOpenJPAIdentity()) { throwException(code, INTERNEXCEP); code.calculateMaxStack(); code.calculateMaxLocals(); return; } // call superclass method if (_meta.getPCSuperclass() != null && !getCreateSubclass()) { loadManagedInstance(code, false); for (int i = 0; i < args.length; i++) code.aload().setParam(i); code.invokespecial().setMethod(getType(_meta.getPCSuperclassMetaData()).getName(), PRE + "CopyKeyFieldsToObjectId", void.class.getName(), args); } // Object id = oid; if (fieldManager) code.aload().setParam(1); else code.aload().setParam(0); if (_meta.isObjectIdTypeShared()) { // oid = ((ObjectId) id).getId (); code.checkcast().setType(ObjectId.class); code.invokevirtual().setMethod(ObjectId.class, "getId", Object.class, null); } // <oid type> id = (<oid type>) oid; int id = code.getNextLocalsIndex(); Class oidType = _meta.getObjectIdType(); code.checkcast().setType(oidType); code.astore().setLocal(id); // int inherited = pcInheritedFieldCount; int inherited = 0; if (fieldManager) { code.getstatic().setField(INHERIT, int.class); inherited = code.getNextLocalsIndex(); code.istore().setLocal(inherited); } // id.<field> = fs.fetch<type>Field (<index>); or... // id.<field> = pc.<field>; FieldMetaData[] fmds = getCreateSubclass() ? _meta.getFields() : _meta.getDeclaredFields(); Class<?> type; String name; Field field; Method setter; boolean reflect; // If optimizeIdCopy is enabled and not a field manager method, try to // optimize the copyTo by using a public constructor instead of reflection if (_optimizeIdCopy) { ArrayList<Integer> pkfields = optimizeIdCopy(oidType, fmds); if (pkfields != null) { // search for a constructor on the IdClass that can be used // to construct the IdClass int parmOrder[] = getIdClassConstructorParmOrder(oidType, pkfields, fmds); if (parmOrder != null) { // If using a field manager, values must be loaded into locals so they can be properly ordered // as constructor parameters. int[] localIndexes = new int[fmds.length]; if (fieldManager) { for (int k = 0; k < fmds.length; k++) { if (!fmds[k].isPrimaryKey()) continue; code.aload().setParam(0); code.constant().setValue(k); code.iload().setLocal(inherited); code.iadd(); code.invokeinterface() .setMethod(getFieldSupplierMethod(fmds[k].getObjectIdFieldType())); localIndexes[k] = code.getNextLocalsIndex(); storeLocalValue(code, localIndexes[k], fmds[k].getObjectIdFieldTypeCode()); } } // found a matching constructor. parm array is constructor parm order code.anew().setType(oidType); code.dup(); // build the parm list in order Class<?>[] clsArgs = new Class<?>[parmOrder.length]; for (int i = 0; i < clsArgs.length; i++) { int parmIndex = parmOrder[i]; clsArgs[i] = fmds[parmIndex].getObjectIdFieldType(); if (!fieldManager) { loadManagedInstance(code, false); addGetManagedValueCode(code, fmds[parmIndex]); } else { // Load constructor parameters in appropriate order loadLocalValue(code, localIndexes[parmIndex], fmds[parmIndex].getObjectIdFieldTypeCode()); if (fmds[parmIndex].getObjectIdFieldTypeCode() == JavaTypes.OBJECT && !fmds[parmIndex].getDeclaredType().isEnum()) { code.checkcast().setType(ObjectId.class); code.invokevirtual().setMethod(ObjectId.class, "getId", Object.class, null); } // if the type of this field meta data is // non-primitive and non-string, be sure to cast // to the appropriate type. if (!clsArgs[i].isPrimitive() && !clsArgs[i].getName().equals(String.class.getName())) code.checkcast().setType(clsArgs[i]); } } // invoke the public constructor to create a new local id code.invokespecial().setMethod(oidType, "<init>", void.class, clsArgs); int ret = code.getNextLocalsIndex(); code.astore().setLocal(ret); // swap out the app id with the new one code.aload().setLocal(fieldManager ? 2 : 1); code.checkcast().setType(ObjectId.class); code.aload().setLocal(ret); code.invokestatic().setMethod(ApplicationIds.class, "setAppId", void.class, new Class[] { ObjectId.class, Object.class }); code.vreturn(); code.calculateMaxStack(); code.calculateMaxLocals(); return; } } } for (int i = 0; i < fmds.length; i++) { if (!fmds[i].isPrimaryKey()) continue; code.aload().setLocal(id); name = fmds[i].getName(); type = fmds[i].getObjectIdFieldType(); if (isFieldAccess(fmds[i])) { setter = null; field = Reflection.findField(oidType, name, true); reflect = !Modifier.isPublic(field.getModifiers()); if (reflect) { code.classconstant().setClass(oidType); code.constant().setValue(name); code.constant().setValue(true); code.invokestatic().setMethod(Reflection.class, "findField", Field.class, new Class[] { Class.class, String.class, boolean.class }); } } else { field = null; setter = Reflection.findSetter(oidType, name, type, true); reflect = !Modifier.isPublic(setter.getModifiers()); if (reflect) { code.classconstant().setClass(oidType); code.constant().setValue(name); code.classconstant().setClass(type); code.constant().setValue(true); code.invokestatic().setMethod(Reflection.class, "findSetter", Method.class, new Class[] { Class.class, String.class, Class.class, boolean.class }); } } if (fieldManager) { code.aload().setParam(0); code.constant().setValue(i); code.iload().setLocal(inherited); code.iadd(); code.invokeinterface().setMethod(getFieldSupplierMethod(type)); if (fmds[i].getObjectIdFieldTypeCode() == JavaTypes.OBJECT && !fmds[i].getDeclaredType().isEnum()) { code.checkcast().setType(ObjectId.class); code.invokevirtual().setMethod(ObjectId.class, "getId", Object.class, null); } // if the type of this field meta data is // non-primitive and non-string, be sure to cast // to the appropriate type. if (!reflect && !type.isPrimitive() && !type.getName().equals(String.class.getName())) code.checkcast().setType(type); } else { loadManagedInstance(code, false); addGetManagedValueCode(code, fmds[i]); // get id/pk from pc instance if (fmds[i].getDeclaredTypeCode() == JavaTypes.PC) addExtractObjectIdFieldValueCode(code, fmds[i]); } if (reflect && field != null) { code.invokestatic().setMethod(Reflection.class, "set", void.class, new Class[] { Object.class, Field.class, (type.isPrimitive()) ? type : Object.class }); } else if (reflect) { code.invokestatic().setMethod(Reflection.class, "set", void.class, new Class[] { Object.class, Method.class, (type.isPrimitive()) ? type : Object.class }); } else if (field != null) code.putfield().setField(field); else code.invokevirtual().setMethod(setter); } code.vreturn(); code.calculateMaxStack(); code.calculateMaxLocals(); }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
@SuppressWarnings("unchecked") protected <OUT, IN1, IN2> TypeInformation<OUT> analyzePojo(Class<OUT> clazz, ArrayList<Type> typeHierarchy, ParameterizedType parameterizedType, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { if (!Modifier.isPublic(clazz.getModifiers())) { LOG.info("Class " + clazz.getName() + " is not public, cannot treat it as a POJO type. Will be handled as GenericType"); return new GenericTypeInfo<OUT>(clazz); }//from w w w.j ava2 s . c o m // add the hierarchy of the POJO itself if it is generic if (parameterizedType != null) { getTypeHierarchy(typeHierarchy, parameterizedType, Object.class); } // create a type hierarchy, if the incoming only contains the most bottom one or none. else if (typeHierarchy.size() <= 1) { getTypeHierarchy(typeHierarchy, clazz, Object.class); } List<Field> fields = getAllDeclaredFields(clazz, false); if (fields.size() == 0) { LOG.info("No fields detected for " + clazz + ". Cannot be used as a PojoType. Will be handled as GenericType"); return new GenericTypeInfo<OUT>(clazz); } List<PojoField> pojoFields = new ArrayList<PojoField>(); for (Field field : fields) { Type fieldType = field.getGenericType(); if (!isValidPojoField(field, clazz, typeHierarchy)) { LOG.info(clazz + " is not a valid POJO type"); return null; } try { ArrayList<Type> fieldTypeHierarchy = new ArrayList<Type>(typeHierarchy); fieldTypeHierarchy.add(fieldType); TypeInformation<?> ti = createTypeInfoWithTypeHierarchy(fieldTypeHierarchy, fieldType, in1Type, in2Type); pojoFields.add(new PojoField(field, ti)); } catch (InvalidTypesException e) { Class<?> genericClass = Object.class; if (isClassType(fieldType)) { genericClass = typeToClass(fieldType); } pojoFields.add(new PojoField(field, new GenericTypeInfo<OUT>((Class<OUT>) genericClass))); } } CompositeType<OUT> pojoType = new PojoTypeInfo<OUT>(clazz, pojoFields); // // Validate the correctness of the pojo. // returning "null" will result create a generic type information. // List<Method> methods = getAllDeclaredMethods(clazz); for (Method method : methods) { if (method.getName().equals("readObject") || method.getName().equals("writeObject")) { LOG.info(clazz + " contains custom serialization methods we do not call."); return null; } } // Try retrieving the default constructor, if it does not have one // we cannot use this because the serializer uses it. Constructor defaultConstructor = null; try { defaultConstructor = clazz.getDeclaredConstructor(); } catch (NoSuchMethodException e) { if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { LOG.info(clazz + " is abstract or an interface, having a concrete " + "type can increase performance."); } else { LOG.info(clazz + " must have a default constructor to be used as a POJO."); return null; } } if (defaultConstructor != null && !Modifier.isPublic(defaultConstructor.getModifiers())) { LOG.info("The default constructor of " + clazz + " should be Public to be used as a POJO."); return null; } // everything is checked, we return the pojo return pojoType; }
From source file:org.apache.openjpa.enhance.PCEnhancer.java
/** * Adds the <code>pcCopyKeyFieldsFromObjectId</code> methods * to classes using application identity. *///from ww w . j a va 2s. c o m private void addCopyKeyFieldsFromObjectIdMethod(boolean fieldManager) throws NoSuchMethodException { // public void pcCopyKeyFieldsFromObjectId (ObjectIdFieldConsumer fc, // Object oid) String[] args = (fieldManager) ? new String[] { OIDFCTYPE.getName(), Object.class.getName() } : new String[] { Object.class.getName() }; BCMethod method = _pc.declareMethod(PRE + "CopyKeyFieldsFromObjectId", void.class.getName(), args); Code code = method.getCode(true); // call superclass method if (_meta.getPCSuperclass() != null && !getCreateSubclass()) { loadManagedInstance(code, false); for (int i = 0; i < args.length; i++) code.aload().setParam(i); code.invokespecial().setMethod(getType(_meta.getPCSuperclassMetaData()).getName(), PRE + "CopyKeyFieldsFromObjectId", void.class.getName(), args); } if (fieldManager) code.aload().setParam(1); else code.aload().setParam(0); if (!_meta.isOpenJPAIdentity() && _meta.isObjectIdTypeShared()) { // oid = ((ObjectId) id).getId (); code.checkcast().setType(ObjectId.class); code.invokevirtual().setMethod(ObjectId.class, "getId", Object.class, null); } // <oid type> cast = (<oid type>) oid; int id = code.getNextLocalsIndex(); Class oidType = _meta.getObjectIdType(); code.checkcast().setType(oidType); code.astore().setLocal(id); // fs.store<type>Field (<index>, id.<field>); or... // this.<field> = id.<field> // or for single field identity: id.getId () FieldMetaData[] fmds = getCreateSubclass() ? _meta.getFields() : _meta.getDeclaredFields(); String name; Class type; Class unwrapped; Field field; Method getter; for (int i = 0; i < fmds.length; i++) { if (!fmds[i].isPrimaryKey()) continue; name = fmds[i].getName(); type = fmds[i].getObjectIdFieldType(); if (!fieldManager && fmds[i].getDeclaredTypeCode() == JavaTypes.PC) { // if (sm == null) return; loadManagedInstance(code, false); code.getfield().setField(SM, SMTYPE); JumpInstruction ifins = code.ifnonnull(); code.vreturn(); // sm.getPCPrimaryKey(oid, i + pcInheritedFieldCount); ifins.setTarget(loadManagedInstance(code, false)); code.dup(); // leave orig on stack to set value into code.getfield().setField(SM, SMTYPE); code.aload().setLocal(id); code.constant().setValue(i); code.getstatic().setField(INHERIT, int.class); code.iadd(); code.invokeinterface().setMethod(StateManager.class, "getPCPrimaryKey", Object.class, new Class[] { Object.class, int.class }); code.checkcast().setType(fmds[i].getDeclaredType()); } else { unwrapped = (fmds[i].getDeclaredTypeCode() == JavaTypes.PC) ? type : unwrapSingleFieldIdentity(fmds[i]); if (fieldManager) { code.aload().setParam(0); code.constant().setValue(i); code.getstatic().setField(INHERIT, int.class); code.iadd(); } else loadManagedInstance(code, false); if (unwrapped != type) { code.anew().setType(type); code.dup(); } code.aload().setLocal(id); if (_meta.isOpenJPAIdentity()) { if (oidType == ObjectId.class) { code.invokevirtual().setMethod(oidType, "getId", Object.class, null); if (!fieldManager && type != Object.class) code.checkcast().setType(fmds[i].getDeclaredType()); } else if (oidType == DateId.class) { code.invokevirtual().setMethod(oidType, "getId", Date.class, null); if (!fieldManager && type != Date.class) code.checkcast().setType(fmds[i].getDeclaredType()); } else { code.invokevirtual().setMethod(oidType, "getId", unwrapped, null); if (unwrapped != type) code.invokespecial().setMethod(type, "<init>", void.class, new Class[] { unwrapped }); } } else if (isFieldAccess(fmds[i])) { field = Reflection.findField(oidType, name, true); if (Modifier.isPublic(field.getModifiers())) code.getfield().setField(field); else { boolean usedFastOid = false; if (_optimizeIdCopy) { // If fastOids, ignore access type and try to use a public getter getter = Reflection.findGetter(oidType, name, false); if (getter != null && Modifier.isPublic(getter.getModifiers())) { usedFastOid = true; code.invokevirtual().setMethod(getter); } } if (!usedFastOid) { // Reflection.getXXX(oid, Reflection.findField(...)); code.classconstant().setClass(oidType); code.constant().setValue(name); code.constant().setValue(true); code.invokestatic().setMethod(Reflection.class, "findField", Field.class, new Class[] { Class.class, String.class, boolean.class }); code.invokestatic().setMethod(getReflectionGetterMethod(type, Field.class)); if (!type.isPrimitive() && type != Object.class) code.checkcast().setType(type); } } } else { getter = Reflection.findGetter(oidType, name, true); if (Modifier.isPublic(getter.getModifiers())) code.invokevirtual().setMethod(getter); else { // Reflection.getXXX(oid, Reflection.findGetter(...)); code.classconstant().setClass(oidType); code.constant().setValue(name); code.constant().setValue(true); code.invokestatic().setMethod(Reflection.class, "findGetter", Method.class, new Class[] { Class.class, String.class, boolean.class }); code.invokestatic().setMethod(getReflectionGetterMethod(type, Method.class)); if (!type.isPrimitive() && type != Object.class) code.checkcast().setType(type); } } } if (fieldManager) code.invokeinterface().setMethod(getFieldConsumerMethod(type)); else addSetManagedValueCode(code, fmds[i]); } code.vreturn(); code.calculateMaxStack(); code.calculateMaxLocals(); }
From source file:mondrian.olap.Util.java
/** * Creates a new udf instance from the given udf class. * * @param udfClass the class to create new instance for * @param functionName Function name, or null * @return an instance of UserDefinedFunction */// ww w . ja v a 2s .co m public static UserDefinedFunction createUdf(Class<? extends UserDefinedFunction> udfClass, String functionName) { // Instantiate class with default constructor. UserDefinedFunction udf; String className = udfClass.getName(); String functionNameOrEmpty = functionName == null ? "" : functionName; // Find a constructor. Constructor<?> constructor; Object[] args = {}; // 0. Check that class is public and top-level or static. // Before JDK 1.5, inner classes are impossible; retroweaver cannot // handle the getEnclosingClass method, so skip the check. if (!Modifier.isPublic(udfClass.getModifiers()) || (!PreJdk15 && udfClass.getEnclosingClass() != null && !Modifier.isStatic(udfClass.getModifiers()))) { throw MondrianResource.instance().UdfClassMustBePublicAndStatic.ex(functionName, className); } // 1. Look for a constructor "public Udf(String name)". try { constructor = udfClass.getConstructor(String.class); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] { functionName }; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } // 2. Otherwise, look for a constructor "public Udf()". if (constructor == null) { try { constructor = udfClass.getConstructor(); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] {}; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } } // 3. Else, no constructor suitable. if (constructor == null) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } // Instantiate class. try { udf = (UserDefinedFunction) constructor.newInstance(args); } catch (InstantiationException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (IllegalAccessException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionName, className, UserDefinedFunction.class.getName()); } catch (ClassCastException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (InvocationTargetException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionName, className, UserDefinedFunction.class.getName()); } return udf; }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
private static boolean checkConstructor(Constructor c, Class clss, List<Class> classes) { if (!Modifier.isPublic(c.getModifiers())) { if (c.getParameterTypes().length != 0 || !Modifier.isProtected(c.getModifiers())) { return true; }/*from ww w . j av a 2s . co m*/ } Constructor ca[] = clss.getDeclaredConstructors(); for (int i = 0; i < ca.length; i++) { Constructor constructor = ca[i]; if (constructor.equals(c)) { break; } if (constructor.getParameterTypes().length == c.getParameterTypes().length) { if (c.getParameterTypes().length >= 1 && String.class.isAssignableFrom(c.getParameterTypes()[0]) != String.class .isAssignableFrom(constructor.getParameterTypes()[0])) { continue; } return true; } } if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) { return true; } if (!checkParameters(c.getParameterTypes(), classes)) { return true; } return false; }
From source file:org.apache.click.util.ClickUtils.java
/** * Invoke the named method on the given target object and return the result. * * @param target the target object with the method to invoke * @param method the name of the method to invoke * @return Object the target method result *///from w ww .j a va 2 s.c om private static Object invokeMethod(Object target, String method) { if (target == null) { throw new IllegalArgumentException("Null target parameter"); } if (method == null) { throw new IllegalArgumentException("Null method parameter"); } Method targetMethod = null; boolean isAccessible = true; try { Class<?> targetClass = target.getClass(); targetMethod = targetClass.getMethod(method); // Change accessible for anonymous inner classes public methods // only. Conditional checks: // #1 - Target method is not accessible // #2 - Anonymous inner classes are not public // #3 - Only modify public methods // #4 - Anonymous inner classes have no declaring class // #5 - Anonymous inner classes have $ in name if (!targetMethod.isAccessible() && !Modifier.isPublic(targetClass.getModifiers()) && Modifier.isPublic(targetMethod.getModifiers()) && targetClass.getDeclaringClass() == null && targetClass.getName().indexOf('$') != -1) { isAccessible = false; targetMethod.setAccessible(true); } return targetMethod.invoke(target); } catch (InvocationTargetException ite) { Throwable e = ite.getTargetException(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Exception) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else if (e instanceof Error) { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } } catch (Exception e) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } finally { if (targetMethod != null && !isAccessible) { targetMethod.setAccessible(false); } } }
From source file:org.apache.openjpa.enhance.PCEnhancer.java
private ArrayList<Integer> optimizeIdCopy(Class<?> oidType, FieldMetaData[] fmds) { // collect all object id fields and verify they // a) have a private field // b) do not have a public setter ArrayList<Integer> pkFields = new ArrayList<Integer>(); // build list of primary key fields for (int i = 0; i < fmds.length; i++) { if (!fmds[i].isPrimaryKey()) continue; // optimizing copy with PC type not (yet) supported if (fmds[i].getDeclaredTypeCode() == JavaTypes.PC) { return null; }/* w w w .jav a2 s .c o m*/ String name = fmds[i].getName(); Field fld = Reflection.findField(oidType, name, false); if (fld == null || Modifier.isPublic(fld.getModifiers())) { return null; } Method setter = Reflection.findSetter(oidType, name, false); if (setter == null || !Modifier.isPublic(setter.getModifiers())) { pkFields.add(i); } else { return null; } } return pkFields.size() > 0 ? pkFields : null; }