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:com.mine.core.util.ReflectUtils.java
/** * , private/protected, ??setter. ignoreNotFond-not found * fieldName/*from w ww .ja v a 2 s . co m*/ */ public static void setFieldValue(final Object obj, final String fieldName, final Object value, boolean ignoreNotFond) { Field field = getAccessibleField(obj, fieldName); if (field == null) { if (ignoreNotFond) { return; } else { throw new IllegalArgumentException("Could not find field [" + fieldName + ERROR_BLOCK + obj + "]"); } } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("??:{}", e.getMessage()); } }
From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java
/** * This will set default on the fields that are marked with a default and * are null// w ww . j a v a2s . co m * * @param entity */ public static void setDefaultsOnFields(Object entity) { Objects.requireNonNull(entity, "Entity must not be NULL"); List<Field> fields = getAllFields(entity.getClass()); for (Field field : fields) { DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class); if (defaultFieldValue != null) { field.setAccessible(true); try { if (field.get(entity) == null) { String value = defaultFieldValue.value(); Class fieldClass = field.getType(); if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) { field.set(entity, value); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) { field.set(entity, value); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) { field.set(entity, Integer.parseInt(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) { field.set(entity, Convert.toBoolean(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) { field.set(entity, Double.parseDouble(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) { field.set(entity, Float.parseFloat(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())) { field.set(entity, Convert.toBigDecimal(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) { field.set(entity, TimeUtil.fromString(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) { field.set(entity, new BigInteger(value)); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new OpenStorefrontRuntimeException( "Unable to get value on " + entity.getClass().getName(), "Check entity passed in."); } } } }
From source file:com.smart.utils.ReflectionUtils.java
/** * ,private/protected,??setter./* www. j ava 2 s. co m*/ */ public static void setFieldValue(final Object object, final String fieldName, final Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { logger.error("??:{}", e); } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static void injectCloudId(Object obj, UUID id) { for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(CloudObjectId.class) != null) { f.setAccessible(true);//from www .ja va 2s . c o m try { if (f.getType().equals(String.class)) f.set(obj, id.toString()); else f.set(obj, id); } catch (Exception e) { e.printStackTrace(); throw new JCloudScaleException(e, "Unexpected error when injecting @CloudObjectId"); } } } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
@SuppressWarnings("unchecked") public static void addInvocationInfo(Object obj, InvocationInfo info) { if (obj == null) return;//from w w w . j a v a2s .c om for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(CloudInvocationInfos.class) != null) { try { f.setAccessible(true); if (f.get(obj) == null) f.set(obj, new LinkedList<InvocationInfo>()); ((List<InvocationInfo>) f.get(obj)).add(info); } catch (Exception e) { e.printStackTrace(); throw new JCloudScaleException(e, "Unexpected error when injecting into @CloudInvocationInfos"); } } } }
From source file:com.ericsson.eif.hansoft.HansoftManager.java
/** * Hansoft adapter properties from adapter.properties * @param servletContext/* w ww . j ava2 s. c om*/ */ private static void init(ServletContext servletContext) { Properties props = new Properties(); try { PROVIDER_CONTEXT_PATH = servletContext.getContextPath(); if (PROVIDER_CONTEXT_PATH.isEmpty()) { String message = "No servlet context name provided, will exit."; logger.error(message); throw new RuntimeException(message); } String adapterHome = System.getenv("ADAPTER_HOME"); if (adapterHome == null) { // default to user home adapterHome = System.getProperty("user.home"); } // The PROVIDER_CONTEXT_PATH has a beginning "/" - remove String contextPath = PROVIDER_CONTEXT_PATH.substring(1); adapterServletHome = adapterHome + File.separator + contextPath; // Need the properties file - if not found, exit try { File propsPath = new File(adapterServletHome + File.separator + "adapter.properties"); if (propsPath.exists()) { props.load(new FileInputStream(propsPath.toString())); } else { String message = "The adapter.properties file not found, will exit."; logger.error(message); throw new RuntimeException(message); } } catch (Exception e) { String message = "Failed to read the adapter.properties file, will exit."; logger.error(message, e); throw new RuntimeException(message); } // It is ok not having a log4j configuration file, but recommended try { File log4jPropsPath = new File(adapterServletHome + File.separator + "log4j.properties"); if (log4jPropsPath.exists()) { // Allow using adapter home path in log4j file System.setProperty("hansoft.adapter_servlet_home", adapterServletHome); PropertyConfigurator.configure(log4jPropsPath.getPath()); } else { logger.warn("The log4j.properties file not found."); } } catch (Exception e) { logger.warn("Failed to read the log4j.properties file.", e); } logger.info("Initialize of Hansoft adapter started ..."); // We need to set the JNI path early, and failed when trying to // pass as input argument. Solution as below is working: // // From // http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/ // // At first the system property is updated with the new value. // This might be a relative path or maybe you want to create that // path dynamically. // // The Classloader has a static field (sys_paths) that contains the // paths. If that field is set to null, it is initialized // automatically. Therefore forcing that field to null will result // into the reevaluation of the library path as soon as // loadLibrary() is called hansoftSDKVersion = props.getProperty("hansoft_sdk_version", "").trim(); if (hansoftSDKVersion == "") { String message = "SDK version not set, will exit."; logger.error(message); throw new RuntimeException(message); } try { hansoftLib = adapterHome + File.separator + "hansoft_libs" + File.separator + hansoftSDKVersion; File libPath = new File(hansoftLib); if (libPath.exists()) { System.setProperty("java.library.path", libPath.toString()); Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); fieldSysPath.setAccessible(true); fieldSysPath.set(null, null); } else { String message = "Hansoft libs for SDK version: " + hansoftSDKVersion + " not found, will exit."; logger.error(message); throw new RuntimeException(message); } } catch (Exception e) { String message = "Failed configuring path for libs for SDK version: " + hansoftSDKVersion + ", will exit."; logger.error(message); throw new RuntimeException(message); } hansoftWorkingDir = props.getProperty("hansoft_working_dir", "").trim(); hansoftChangeLogDir = props.getProperty("hansoft_change_log_dir", "").trim(); hansoftLogDir = props.getProperty("hansoft_log_dir", "").trim(); hansoftServer = props.getProperty("hansoft_server", "").trim(); hansoftPort = Integer.parseInt(props.getProperty("hansoft_port", "-1")); hansoftDatabase = props.getProperty("hansoft_database", "").trim(); hansoftSDK = props.getProperty("hansoft_sdk_user", "").trim(); hansoftSDKPassword = props.getProperty("hansoft_sdk_password", "").trim(); hansoftAdapterServer = props.getProperty("hansoft_adapter_server", "").trim(); hansoftAdapterServerScheme = props.getProperty("hansoft_adapter_server_scheme", "http").trim(); hansoftAdapterServerPort = props.getProperty("hansoft_adapter_server_port", "8080").trim(); validate_h2h_config = props.getProperty("validate_h2h_config", "false").trim(); h2h_config_validation_output_to_file = props.getProperty("h2h_config_validation_output_to_file", "true") .trim(); h2h_config_validation_output_on_screen = props .getProperty("h2h_config_validation_output_on_screen", "true").trim(); OSLC_BACKLINK_COL_NAME = props.getProperty("hansoft_backlink", "OSLC Reference").trim(); String FPs = props.getProperty("hansoft_fps", "").trim(); setHansoftFPs(FPs); logger.log(Level.INFO, "Property hansoft_adapter_server = " + hansoftAdapterServer); logger.log(Level.INFO, "Property hansoft_adapter_server_scheme = " + hansoftAdapterServerScheme); logger.log(Level.INFO, "Property hansoft_adapter_server_port = " + hansoftAdapterServerPort); logger.log(Level.INFO, "Property hansoft_working_dir = " + hansoftWorkingDir); logger.log(Level.INFO, "Property hansoft_change_log_dir = " + hansoftChangeLogDir); logger.log(Level.INFO, "Property hansoft_log_dir = " + hansoftLogDir); logger.log(Level.INFO, "Property hansoft_server = " + hansoftServer); logger.log(Level.INFO, "Property hansoft_port = " + hansoftPort); logger.log(Level.INFO, "Property hansoft_database = " + hansoftDatabase); logger.log(Level.INFO, "Property hansoft_sdk_user = " + hansoftSDK); logger.log(Level.INFO, "Property hansoft_sdk_version = " + hansoftSDKVersion); logger.log(Level.INFO, "Property validate_h2h_config = " + validate_h2h_config); logger.log(Level.INFO, "Property h2h_config_validation_output_to_file = " + h2h_config_validation_output_to_file); logger.log(Level.INFO, "Property h2h_config_validation_output_on_screen = " + h2h_config_validation_output_on_screen); getMainSession(); loadH2HConfiguration(); if (validate_h2h_config.equalsIgnoreCase("true")) { validateH2Hconfiguration(); } QSchedule.getInstance(); } catch (SecurityException | IllegalArgumentException | HPMSdkException | HPMSdkJavaException e) { logger.error("Failed during static init of Hansoft Adapter", e); } }
From source file:com.nerve.commons.repository.utils.reflection.ReflectionUtils.java
/** * , private/protected, ??setter.// w ww .j a va2 s . c o m */ public static void setFieldValue(final Object obj, final String fieldName, final Object value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } try { field.set(obj, value); } catch (IllegalAccessException e) { e.printStackTrace(); logger.error("??:{}", e.getMessage()); } }
From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
public static void injectEventSink(Object obj) { for (Field f : obj.getClass().getDeclaredFields()) { if (f.getAnnotation(EventSink.class) != null) { f.setAccessible(true);//from www . jav a 2s . com if (IEventSink.class.isAssignableFrom(f.getType())) try { f.set(obj, new DefaultEventSink()); } catch (Exception e) { throw new JCloudScaleException(e, "Unexpected error when injecting into @EventSink"); } else throw new JCloudScaleException("Cannot inject event sink into field " + f.getName() + ". " + "Type needs to be IEventSink, but is " + f.getType().getCanonicalName()); } } }
From source file:com.app.test.BaseTestCase.java
protected static void _initializeVelocityTemplate(Class clazz, Object classInstance) throws Exception { Field velocityEngine = clazz.getDeclaredField("_velocityEngine"); velocityEngine.setAccessible(true);/*from www. ja v a 2 s . com*/ VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean(); Map<String, Object> velocityPropertiesMap = new HashMap<>(); velocityPropertiesMap.put("resource.loader", "class"); velocityPropertiesMap.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader." + "ClasspathResourceLoader"); velocityEngineFactoryBean.setVelocityPropertiesMap(velocityPropertiesMap); velocityEngine.set(classInstance, velocityEngineFactoryBean.createVelocityEngine()); }
From source file:com.aliyun.odps.ship.upload.BlockRecordReaderTest.java
public static void setSystemDefaultCharset(String s) throws NoSuchFieldException, IllegalAccessException { System.setProperty("file.encoding", s); Field charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true);/*from w ww .ja v a 2 s. co m*/ charset.set(null, null); }