List of usage examples for java.lang.reflect Field set
@CallerSensitive @ForceInline public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException
From source file:net.ceos.project.poi.annotated.core.CellHandler.java
/** * Read an enumeration value from the Cell. * /*from ww w. j a va 2s . co m*/ * @param object * the object * @param fT * the class of the field * @param field * the {@link Field} to set * @param cell * the {@link Cell} to read * @throws ConverterException * the conversion exception type */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected static void enumReader(final Object object, final Class<?> fT, final Field field, final Cell cell) throws ConverterException { if (StringUtils.isNotBlank(cell.getStringCellValue())) { try { field.set(object, Enum.valueOf((Class<Enum>) fT, cell.getStringCellValue())); } catch (IllegalArgumentException | IllegalAccessException e) { throw new ConverterException(ExceptionMessage.CONVERTER_ENUM.getMessage(), e); } } }
From source file:com.espertech.esper.util.PopulateUtil.java
public static void populateObject(String operatorName, int operatorNum, String dataFlowName, Map<String, Object> objectProperties, Object top, EngineImportService engineImportService, EPDataFlowOperatorParameterProvider optionalParameterProvider, Map<String, Object> optionalParameterURIs) throws ExprValidationException { Class applicableClass = top.getClass(); Set<WriteablePropertyDescriptor> writables = PropertyHelper.getWritableProperties(applicableClass); Set<Field> annotatedFields = JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class); Set<Method> annotatedMethods = JavaClassHelper.findAnnotatedMethods(top.getClass(), DataFlowOpParameter.class); // find catch-all methods Set<Method> catchAllMethods = new LinkedHashSet<Method>(); if (annotatedMethods != null) { for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { catchAllMethods.add(method); continue; }//from w w w . jav a 2 s. c om throw new ExprValidationException("Invalid annotation for catch-call"); } } } // map provided values for (Map.Entry<String, Object> property : objectProperties.entrySet()) { boolean found = false; String propertyName = property.getKey(); // invoke catch-all setters for (Method method : catchAllMethods) { try { method.invoke(top, new Object[] { propertyName, property.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } found = true; } if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) { continue; } // use the writeable property descriptor (appropriate setter method) from writing the property WriteablePropertyDescriptor descriptor = findDescriptor(applicableClass, propertyName, writables); if (descriptor != null) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), descriptor.getType(), engineImportService, false); try { descriptor.getWriteMethod().invoke(top, new Object[] { coerceProperty }); } catch (IllegalArgumentException e) { throw new ExprValidationException("Illegal argument invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + " provided value " + coerceProperty, e); } catch (IllegalAccessException e) { throw new ExprValidationException("Illegal access invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException("Exception invoking setter method for property '" + propertyName + "' for class " + applicableClass.getName() + " method " + descriptor.getWriteMethod().getName() + ": " + e.getTargetException().getMessage(), e); } continue; } // find the field annotated with {@link @GraphOpProperty} for (Field annotatedField : annotatedFields) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations()).get(0); if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) { Object coerceProperty = coerceProperty(propertyName, applicableClass, property.getValue(), annotatedField.getType(), engineImportService, true); try { annotatedField.setAccessible(true); annotatedField.set(top, coerceProperty); } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } found = true; break; } } if (found) { continue; } throw new ExprValidationException("Failed to find writable property '" + propertyName + "' for class " + applicableClass.getName()); } // second pass: if a parameter URI - value pairs were provided, check that if (optionalParameterURIs != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); String uri = operatorName + "/" + annotatedField.getName(); if (optionalParameterURIs.containsKey(uri)) { Object value = optionalParameterURIs.get(uri); annotatedField.set(top, value); if (log.isDebugEnabled()) { log.debug("Found parameter '" + uri + "' for data flow " + dataFlowName + " setting " + value); } } else { if (log.isDebugEnabled()) { log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName); } } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } for (Method method : annotatedMethods) { DataFlowOpParameter anno = (DataFlowOpParameter) JavaClassHelper .getAnnotations(DataFlowOpParameter.class, method.getDeclaredAnnotations()).get(0); if (anno.all()) { if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == String.class && method.getParameterTypes()[1] == Object.class) { for (Map.Entry<String, Object> entry : optionalParameterURIs.entrySet()) { String[] elements = URIUtil.parsePathElements(URI.create(entry.getKey())); if (elements.length < 2) { throw new ExprValidationException("Failed to parse URI '" + entry.getKey() + "', expected " + "'operator_name/property_name' format"); } if (elements[0].equals(operatorName)) { try { method.invoke(top, new Object[] { elements[1], entry.getValue() }); } catch (IllegalAccessException e) { throw new ExprValidationException( "Illegal access invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName(), e); } catch (InvocationTargetException e) { throw new ExprValidationException( "Exception invoking method for property '" + entry.getKey() + "' for class " + applicableClass.getName() + " method " + method.getName() + ": " + e.getTargetException().getMessage(), e); } } } } } } } // third pass: if a parameter provider is provided, use that if (optionalParameterProvider != null) { for (Field annotatedField : annotatedFields) { try { annotatedField.setAccessible(true); Object provided = annotatedField.get(top); Object value = optionalParameterProvider.provide(new EPDataFlowOperatorParameterProviderContext( operatorName, annotatedField.getName(), top, operatorNum, provided, dataFlowName)); if (value != null) { annotatedField.set(top, value); } } catch (Exception e) { throw new ExprValidationException( "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e); } } } }
From source file:com.bizcreator.core.config.FieldInfo.java
public void injectProperty(Object object, ObjectFactoryImpl objectFactory) { Object propertyValue = objectFactory.getObject(propertyValueInfo); Field propertyField = findField(object.getClass()); propertyField.setAccessible(true);/* w w w .j av a2s. c o m*/ try { propertyField.set(object, propertyValue); } catch (Exception e) { throw new BaseException("couldn't set field '" + propertyName + "' on class '" + object.getClass() + "' to value '" + propertyValue + "'", e); } }
From source file:com.vmware.qe.framework.datadriven.impl.injector.DataInjectorUsingReflection.java
@Override public void inject(Object test, HierarchicalConfiguration data, HierarchicalConfiguration context) { String propertyName = context.getString(TAG_DATA_INJECTOR_PROPERTY, null); propertyName = propertyName == null//from w w w . j ava 2s . co m ? DDConfig.getSingleton().getData().getString(TAG_DATA_INJECTOR_PROPERTY, DATA_INJECTOR_DEFAULT_PROPERTY_NAME) : propertyName; Class<? extends Object> testClass = test.getClass(); Field field; try { field = getField(testClass, propertyName); field.setAccessible(true); field.set(test, data); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new DDException("Failed to inject data to property with name =" + propertyName, e); } }
From source file:com.liferay.portal.velocity.LiferayResourceManager.java
@Override public synchronized void initialize(RuntimeServices runtimeServices) throws Exception { ExtendedProperties extendedProperties = runtimeServices.getConfiguration(); Field field = ReflectionUtil.getDeclaredField(RuntimeInstance.class, "configuration"); field.set(runtimeServices, new FastExtendedProperties(extendedProperties)); super.initialize(runtimeServices); }
From source file:Main.java
public final static void fixPopupWindow(final PopupWindow window) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try {/*from w w w . jav a 2 s .c o m*/ final Field mAnchorField = PopupWindow.class.getDeclaredField("mAnchor"); mAnchorField.setAccessible(true); Field mOnScrollChangedListenerField = PopupWindow.class .getDeclaredField("mOnScrollChangedListener"); mOnScrollChangedListenerField.setAccessible(true); final OnScrollChangedListener mOnScrollChangedListener = (OnScrollChangedListener) mOnScrollChangedListenerField .get(window); OnScrollChangedListener newListener = new OnScrollChangedListener() { public void onScrollChanged() { try { WeakReference<?> mAnchor = WeakReference.class.cast(mAnchorField.get(window)); Object anchor = mAnchor != null ? mAnchor.get() : null; if (anchor == null) { return; } else { mOnScrollChangedListener.onScrollChanged(); } } catch (Exception e) { e.printStackTrace(); } } }; mOnScrollChangedListenerField.set(window, newListener); } catch (Exception e) { } } }
From source file:org.zephyrsoft.sdb2.Start.java
private Start(String[] args) { LOG.debug("starting application"); // parse command line arguments CmdLineParser parser = new CmdLineParser(options); parser.setUsageWidth(80);/* w ww .j a v a2s .c om*/ try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); options.setHelp(true); } if (options.isHelp()) { System.err.println("The available options are:"); parser.printUsage(System.err); } else { try { // set encoding to UTF-8 (the cache has to be reset to make the new definition effective) System.setProperty("file.encoding", "UTF-8"); Field charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true); charset.set(null, null); LOG.info("default time zone is {}", ZoneId.systemDefault().getId()); LOG.info("loading application context"); @SuppressWarnings("resource") AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(SpringConfiguration.class); context.refresh(); context.getAutowireCapableBeanFactory().autowireBean(this); mainController.loadSongs(options.getSongsFile()); mainWindow.startup(); } catch (Exception e) { LOG.error("problem while starting up the application", e); System.exit(-1); } } }
From source file:com.haulmont.cuba.core.sys.jmx.MBeanExporter.java
public MBeanExporter() { setAssembler(new AnnotationMBeanInfoAssembler()); // hack logging try {/*from w w w . j a v a2 s. c o m*/ Field loggerField = MBeanRegistrationSupport.class.getDeclaredField("logger"); loggerField.setAccessible(true); loggerField.set(this, LogFactory.getLog(org.springframework.jmx.export.MBeanExporter.class)); } catch (NoSuchFieldException | IllegalAccessException ignore) { } }
From source file:com.shigengyu.hyperion.cache.WorkflowStateCacheLoader.java
@Override @Transactional// www.j av a2 s .c o m public WorkflowState load(final Class<? extends WorkflowState> key) { WorkflowState workflowState; try { workflowState = key.newInstance(); StateOwner stateOwner = getStateOwner(key); if (stateOwner != null) { Field field = WorkflowState.class.getDeclaredField("stateOwner"); field.setAccessible(true); field.set(workflowState, stateOwner); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException e) { throw new WorkflowStateException( StringMessage.with("Failed to create workflow state instance of type [{}]", key.getName()), e); } catch (NoSuchFieldException e) { throw new WorkflowStateException("Failed to get stateOwner field in WorkflowState class", e); } workflowStateDao.saveOrUpdate(workflowState.toEntity()); return workflowState; }
From source file:de.widone.web.HomePageTest.java
@Before public void setUp() throws Exception { User user = new User(); user.setUsername("username"); user.setGroup(GroupsEnum.USER);//w w w . j a v a2s. co m List<TaskList> taskLists = new ArrayList<TaskList>(); TaskList taskList = new TaskList(); taskList.setInbox(Boolean.TRUE); taskList.setDescription("The default inbox"); taskLists.add(taskList); user.setTaskLists(taskLists); tester = new WicketTester(new WiDoneApplication()); when(userService.initTaskLists(Matchers.<User>any())).thenReturn(user); Field userField = ReflectionUtils.findField(WiDoneSession.class, "user"); ReflectionUtils.makeAccessible(userField); userField.set(((WiDoneSession) tester.getSession()), user); }