List of usage examples for java.lang.reflect Method isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:org.apache.ojb.broker.metadata.ClassDescriptor.java
/** * Specify the method to instantiate objects * represented by this descriptor.//from w ww . j av a2 s . c om * @see #setFactoryClass */ private synchronized void setFactoryMethod(Method newMethod) { if (newMethod != null) { // make sure it's a no argument method if (newMethod.getParameterTypes().length > 0) { throw new MetadataException("Factory methods must be zero argument methods: " + newMethod.getClass().getName() + "." + newMethod.getName()); } // make it accessible if it's not already if (!newMethod.isAccessible()) { newMethod.setAccessible(true); } } this.factoryMethod = newMethod; }
From source file:org.apache.ojb.broker.metadata.ClassDescriptor.java
/** * sets the initialization method for this descriptor */// w ww.j av a2 s .c o m private synchronized void setInitializationMethod(Method newMethod) { if (newMethod != null) { // make sure it's a no argument method if (newMethod.getParameterTypes().length > 0) { throw new MetadataException("Initialization methods must be zero argument methods: " + newMethod.getClass().getName() + "." + newMethod.getName()); } // make it accessible if it's not already if (!newMethod.isAccessible()) { newMethod.setAccessible(true); } } this.initializationMethod = newMethod; }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * /* w ww . j a va 2 s . c om*/ * @param entity * @param includeTransient * @return * @throws IllegalArgumentException */ public List<MarshalledField> marshallOut(Object entity, boolean includeTransient) throws IllegalArgumentException { TreeSet<MarshalledField> fields = new TreeSet<MarshalledField>(); if (entity == null) { for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { fields.add(new MarshalledField(ent.getKey().getName())); } return new LinkedList<MarshalledField>(fields); } log.debug("Marshalling out instance of " + entity.getClass().getSimpleName()); Field field; Converter converter; Object value; Method getter; boolean error = false; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { error = false; field = ent.getKey(); converter = ent.getValue(); value = null; log.debug("Converting field " + field.getName()); if ((field.isAnnotationPresent(Transient.class) || Modifier.isTransient(field.getModifiers())) && !includeTransient) continue; try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { value = convertNull(field.get(entity)); } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to access " + entity.getClass().getSimpleName() + "." + field.getName() + " directly.", iae); error = true; } if (error) { error = false; try { getter = converter.getGetter(); if (getter != null) { if (!getter.isAccessible()) { getter.setAccessible(true); } if (getter.isAccessible()) { value = convertNull(getter.invoke(entity)); } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing getter for field " + entity.getClass().getSimpleName() + "." + field.getName(), iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking getter for field " + entity.getClass().getSimpleName() + "." + field.getName(), ite); error = true; } } if (error) { // if there was an error, then we weren't able to access the field, // so set the value to be displayed to "Inaccessible!" and override // the converter readonly value to make sure the display doesn't let // the user edit an inaccessible field. converter.setReadOnly(true); fields.add(new MarshalledField(field.getName(), "Inaccessible!", converter)); } else { fields.add(new MarshalledField(field.getName(), value, converter)); } } return new LinkedList<MarshalledField>(fields); }
From source file:org.wisdom.wamp.WampController.java
private void handleRPCInvocation(WampClient client, String callId, ExportedService service, String method, List<JsonNode> args) { // Find method using reflection Method[] methods = service.service.getClass().getMethods(); Method callback = null; for (Method m : methods) { if (m.getName().equals(method)) { callback = m;/*from w ww.j a v a 2 s . co m*/ break; } } if (callback == null) { LOGGER.error("Invalid CALL message, cannot find method {} in class {}", method, service.service.getClass().getName()); sendOnWebSocket(new RPCError(callId, new UnsupportedOperationException( "Cannot find method " + method + " in " + service.service.getClass().getName()), errorPrefix).toJson(json), client); return; } // IMPORTANT: method name must be unique. // Callback found, wrap arguments. Object[] arguments = new Object[callback.getParameterTypes().length]; if (args.size() != arguments.length) { LOGGER.error("Invalid CALL message, the method {} exists in class {}, but the number of arguments does " + "not match the RPC request", method, service.service.getClass().getName()); sendOnWebSocket( new RPCError(callId, new UnsupportedOperationException("Argument mismatch, " + "expecting " + arguments.length + ", received " + args.size() + " values"), errorPrefix).toJson(json), client); return; } for (int i = 0; i < arguments.length; i++) { Class<?> type = callback.getParameterTypes()[i]; JsonNode node = args.get(i); Object value = json.fromJson(node, type); arguments[i] = value; } // Invoke and send Object result; try { if (!callback.isAccessible()) { callback.setAccessible(true); } result = callback.invoke(service.service, arguments); RPCResult message = new RPCResult(callId, result); sendOnWebSocket(message.toJson(json), client); } catch (IllegalAccessException e) { LOGGER.error("Invalid CALL message, the method {} from class {} is not accessible", method, service.service.getClass().getName(), e); sendOnWebSocket(new RPCError(callId, e, "cannot access method " + callback.getName() + " from " + service.service.getClass().getName(), errorPrefix).toJson(json), client); } catch (InvocationTargetException e) { //NOSONAR LOGGER.error("Invalid CALL message, the method {} from class {} has thrown an exception", method, service.service.getClass().getName(), e.getCause()); sendOnWebSocket( new RPCError(callId, e.getTargetException(), "error while invoking " + callback.getName() + " " + "from " + service.service.getClass().getName(), errorPrefix).toJson(json), client); } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
/** * Returns a {@link Method} with a certain name and parameter types declared in the given class or any subclass * (except {@link Object})./*from w w w . j a va 2s . com*/ * <p/> * If no parameter types are specified i.e., {@code paramTypes} is {@code null} the parameter types are ignored * for signature comparison.<br/> * If a parameter type is not known i.e., it is {@code null}, all declared methods are checked whether their * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter * type of the method and if exactly one was found, it is returned.<br/> * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several methods were found. * * @param type the class * @param methodName the name of the method to find * @param clazzes the full-qualified class names of the parameters * @return the accessible method resolved * @throws ClassNotFoundException if a class cannot be located by the specified class loader */ public static Method findMethod(final Class<?> type, String methodName, Class<?>... clazzes) throws ClassNotFoundException { Method method = null; // If all parameter types are known, find the method that exactly matches the signature if (clazzes != null && !ArrayUtils.contains(clazzes, null)) { for (Class<?> clazz = type; clazz != Object.class; clazz = clazz.getSuperclass()) { try { method = type.getDeclaredMethod(methodName, clazzes); break; } catch (NoSuchMethodException e) { // Ignore } } } // If no method was found, find all possible candidates if (method == null) { List<Method> candidates = new ArrayList<>(); for (Class<?> clazz = type; clazz != null; clazz = clazz.getSuperclass()) { for (Method declaredMethod : clazz.getDeclaredMethods()) { if (declaredMethod.getName().equals(methodName) && (clazzes == null || ClassUtils.isAssignable(clazzes, declaredMethod.getParameterTypes()))) { // Check if there is already a overridden method with the same signature for (Method candidate : candidates) { if (candidate.getName().equals(declaredMethod.getName())) { /** * If there is at least one parameters in the method of the super type, which is a * sub type of the corresponding parameter of the sub type, remove the method declared * in the sub type. */ if (!Arrays.equals(declaredMethod.getParameterTypes(), candidate.getParameterTypes()) && ClassUtils.isAssignable(declaredMethod.getParameterTypes(), candidate.getParameterTypes())) { candidates.remove(candidate); } else { declaredMethod = null; } break; } } // If the method has a different signature matching the given types, add it to the candidates if (declaredMethod != null) { candidates.add(declaredMethod); } } } } if (candidates.size() != 1) { throw new JCloudScaleException( String.format("Cannot find distinct method '%s.%s()' with parameter types %s", type, methodName, Arrays.toString(clazzes))); } method = candidates.get(0); } //do we really need this dependency? //ReflectionUtils.makeAccessible(method); if (method != null && !method.isAccessible()) method.setAccessible(true); return method; }
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 ww w .j a v a2 s . com*/ 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.j2free.admin.ReflectionMarshaller.java
/** * /* ww w .j a v a 2 s . c o m*/ * @param entity * @param parameterMap * @param controller * @return * @throws MarshallingException */ public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller) throws MarshallingException { Field field; Converter converter; Method setter; String[] newValues; log.debug("Marshalling in instance of " + entity.getClass().getSimpleName()); boolean error = false, success = false, isEntity = false, isCollection = false; Class collectionType; Class fieldType; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { // reset flags error = success = isEntity = isCollection = false; field = ent.getKey(); converter = ent.getValue(); if (converter.isReadOnly()) { log.debug("Skipping read-only field " + field.getName()); continue; } newValues = parameterMap.get(field.getName()); if (newValues == null || newValues.length == 0) { log.debug("Skipping field " + field.getName() + ", no new value set."); continue; } isEntity = converter.isEntity(); isCollection = converter.isCollection(); fieldType = field.getType(); collectionType = isCollection ? converter.getType() : null; log.debug("Marshalling in field " + field.getName()); // try to get the original value try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { log.debug(field.getName() + " is accessible"); if (!isEntity && !isCollection) { log.debug("!isEntity && !isCollection"); // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } field.set(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isChar(fieldType)) { field.set(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } field.set(entity, newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { field.set(entity, fieldType.cast(newValues[0])); log.debug("Assigned via cast"); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType) && !newValues[0].equals("")) { field.setInt(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType) && !newValues[0].equals("")) { field.setFloat(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType) && !newValues[0].equals("")) { field.setDouble(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType) && !newValues[0].equals("")) { field.setShort(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { field.setChar(entity, newValues[0].charAt(0)); } else if (isLong(fieldType) && !newValues[0].equals("")) { field.setLong(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType) && !newValues[0].equals("")) { field.setBoolean(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType) && !newValues[0].equals("")) { field.setByte(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { field.set(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else if (!newValues[0].equals("")) { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); field.set(entity, fieldType.cast(newValues[0])); } else if (newValues[0].equals("")) { log.debug("Skipping field " + field.getName() + ", empty string value passed in."); } } } } else if (isEntity && !isCollection) { log.debug("isEntity && !isCollection"); ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { log.debug("!isEntity && isCollection"); throw new MarshallingException("Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { log.debug("isEntity && isCollection"); // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); log.debug("newValues.length = " + newValues.length); log.debug("newValues[0] = " + newValues[0]); log.debug("idsString.length = " + idsString.length); if (collection == null) collection = new LinkedList(); collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); log.debug("CollectionType = " + collectionType.getName()); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add( controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } field.set(entity, collection); } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to set " + field.getName() + " directly.", iae); error = true; } catch (ClassCastException cce) { log.error("Error setting " + field.getName() + ".", cce); error = true; } // if we hit an error getting it directly, try via the getter if (error) { error = false; try { setter = converter.getSetter(); if (setter != null) { if (!setter.isAccessible()) { setter.setAccessible(true); } if (setter.isAccessible()) { if (!isEntity && !isCollection) { // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } setter.invoke(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isChar(fieldType)) { setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, (Object[]) newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { setter.invoke(entity, fieldType.cast(newValues[0])); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType)) { setter.invoke(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType)) { setter.invoke(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType)) { setter.invoke(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType)) { setter.invoke(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { setter.invoke(entity, newValues[0].charAt(0)); } else if (isLong(fieldType)) { setter.invoke(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType)) { setter.invoke(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType)) { setter.invoke(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { setter.invoke(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); setter.invoke(entity, fieldType.cast(newValues[0])); } } } } else if (isEntity && !isCollection) { ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); setter.invoke(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { throw new MarshallingException( "Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); if (collection == null) collection = new LinkedList(); if (idsString.length == 0 && collection.isEmpty()) continue; collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add(controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } setter.invoke(entity, collection); } } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing setter", iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking setter", ite); error = true; } } if (error) { throw new MarshallingException("Unable to marshall in field " + field.getName() + "."); } } return entity; }