List of usage examples for java.lang.reflect Field getLong
@CallerSensitive @ForceInline public long getLong(Object obj) throws IllegalArgumentException, IllegalAccessException
From source file:cn.edu.zafu.corepage.base.BaseActivity.java
/** * ??/* ww w . ja v a2 s .c o m*/ * * @param outState Bundle */ @Override protected void onSaveInstanceState(Bundle outState) { Field[] fields = this.getClass().getDeclaredFields(); Field.setAccessible(fields, true); Annotation[] ans; for (Field f : fields) { ans = f.getDeclaredAnnotations(); for (Annotation an : ans) { if (an instanceof SaveWithActivity) { try { Object o = f.get(this); if (o == null) { continue; } String fieldName = f.getName(); if (o instanceof Integer) { outState.putInt(fieldName, f.getInt(this)); } else if (o instanceof String) { outState.putString(fieldName, (String) f.get(this)); } else if (o instanceof Long) { outState.putLong(fieldName, f.getLong(this)); } else if (o instanceof Short) { outState.putShort(fieldName, f.getShort(this)); } else if (o instanceof Boolean) { outState.putBoolean(fieldName, f.getBoolean(this)); } else if (o instanceof Byte) { outState.putByte(fieldName, f.getByte(this)); } else if (o instanceof Character) { outState.putChar(fieldName, f.getChar(this)); } else if (o instanceof CharSequence) { outState.putCharSequence(fieldName, (CharSequence) f.get(this)); } else if (o instanceof Float) { outState.putFloat(fieldName, f.getFloat(this)); } else if (o instanceof Double) { outState.putDouble(fieldName, f.getDouble(this)); } else if (o instanceof String[]) { outState.putStringArray(fieldName, (String[]) f.get(this)); } else if (o instanceof Parcelable) { outState.putParcelable(fieldName, (Parcelable) f.get(this)); } else if (o instanceof Serializable) { outState.putSerializable(fieldName, (Serializable) f.get(this)); } else if (o instanceof Bundle) { outState.putBundle(fieldName, (Bundle) f.get(this)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } super.onSaveInstanceState(outState); }
From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java
@Override public final int hashCode() { int result = 0; Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { // compare non-final, non-static and non-transient fields only if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { try { // skip arrays if (!field.getType().isArray() && field.get(this) != null) { // for string take its length if (field.getType().equals(String.class)) { result ^= ((String) field.get(this)).length(); } else if (field.getType().equals(short.class) || field.getType().equals(Short.class)) { result ^= field.getShort(this); } else if (field.getType().equals(int.class) || field.getType().equals(Integer.class)) { result ^= field.getInt(this); } else if (field.getType().equals(float.class) || field.getType().equals(Float.class)) { result ^= (int) field.getFloat(this); } else if (field.getType().equals(double.class) || field.getType().equals(Double.class)) { result ^= (int) field.getDouble(this); } else if (field.getType().equals(long.class) || field.getType().equals(Long.class)) { result ^= (int) field.getLong(this); } else if (field.getType().equals(byte.class) || field.getType().equals(Byte.class)) { result ^= field.getByte(this); } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { result ^= field.getBoolean(this) == Boolean.TRUE ? 1 : 0; }/* w w w.ja va2 s . c o m*/ } } catch (Exception e) { log.error(e.toString()); throw new RuntimeException("Exception caught while calculating HardwareAddress hashcode.", e); } } } return result; }
From source file:org.rhq.enterprise.gui.legacy.taglib.ConstantsTag.java
public int doEndTag() throws JspException { try {//from ww w .j a v a 2s. c o m JspWriter out = pageContext.getOut(); if (className == null) { className = pageContext.getServletContext().getInitParameter(constantsClassNameParam); } if (validate(out)) { // we're misconfigured. getting this far // is a matter of what our failure mode is; // if we haven't thrown an Error, carry on log.debug("constants tag misconfigured"); return EVAL_PAGE; } Map<String, String> fieldMap; if (constants.containsKey(className)) { // we cache the result of the constant's class // reflection field walk as a map fieldMap = (Map<String, String>) constants.get(className); } else { fieldMap = new HashMap<String, String>(); Class typeClass = Class.forName(className); if (typeClass.isEnum()) { for (Object enumConstantObj : typeClass.getEnumConstants()) { Enum enumConstant = (Enum) enumConstantObj; // Set name *and* value to enum name (e.g. name of ResourceCategory.PLATFORM = "PLATFORM") // NOTE: We do not set the value to enumConstant.ordinal(), because there is no way to // convert the ordinal value back to an Enum (i.e. no Enum.valueOf(int ordinal) method). fieldMap.put(enumConstant.name(), enumConstant.name()); } } else { Object instance = typeClass.newInstance(); Field[] fields = typeClass.getFields(); for (Field field : fields) { // string comparisons of class names should be cheaper // than reflective Class comparisons, the asumption here // is that most constants are Strings, ints and booleans // but a minimal effort is made to accomadate all types // and represent them as String's for our tag's output String fieldType = field.getType().getName(); String strVal; if (fieldType.equals("java.lang.String")) { strVal = (String) field.get(instance); } else if (fieldType.equals("int")) { strVal = Integer.toString(field.getInt(instance)); } else if (fieldType.equals("boolean")) { strVal = Boolean.toString(field.getBoolean(instance)); } else if (fieldType.equals("char")) { strVal = Character.toString(field.getChar(instance)); } else if (fieldType.equals("double")) { strVal = Double.toString(field.getDouble(instance)); } else if (fieldType.equals("float")) { strVal = Float.toString(field.getFloat(instance)); } else if (fieldType.equals("long")) { strVal = Long.toString(field.getLong(instance)); } else if (fieldType.equals("short")) { strVal = Short.toString(field.getShort(instance)); } else if (fieldType.equals("byte")) { strVal = Byte.toString(field.getByte(instance)); } else { strVal = field.get(instance).toString(); } fieldMap.put(field.getName(), strVal); } } // cache the result constants.put(className, fieldMap); } if ((symbol != null) && !fieldMap.containsKey(symbol)) { // tell the developer that he's being a dummy and what // might be done to remedy the situation // TODO: what happens if the constants change? // do we need to throw a JspException, here? - mtk String err1 = symbol + " was not found in " + className + "\n"; String err2 = err1 + "use <constants:diag classname=\"" + className + "\"/>\n" + "to figure out what you're looking for"; log.error(err2); die(out, err1); } if (varSpecified) { doSet(fieldMap); } else { doOutput(fieldMap, out); } } catch (JspException e) { throw e; } catch (Exception e) { log.debug("doEndTag() failed: ", e); throw new JspException("Could not access constants tag", e); } return EVAL_PAGE; }
From source file:at.treedb.backup.Import.java
private void adjustFields(DAOiface dao, Class<?> c, Iterator iter) throws Exception { ArrayList<Field> list = ClassDependency.getAllFields(c); ArrayList<Field> dbKeys = new ArrayList<Field>(); ArrayList<Field> detached = new ArrayList<Field>(); // System.out.println("adjust class:" + c.getSimpleName() + ":"); for (Field f : list) { f.setAccessible(true);// w w w . jav a2 s . c o m if (f.getAnnotation(Detach.class) != null) { detached.add(f); } else if (f.getAnnotation(DBkey.class) != null) { dbKeys.add(f); } } HashMap<Integer, Integer> detachMap = detachIdMap.get(c); HashMap<Integer, Integer> historicMap = historicIdMap.get(c); while (iter.hasNext()) { List<Object> l = iter.next(); for (Object o : l) { Base b = (Base) o; for (Field f : dbKeys) { f.setAccessible(true); Class<?> clazz = f.getAnnotation(DBkey.class).value(); HashMap<Integer, Integer> idMap; Class<?> sel = null; // ClassSelector necessary for ID re-mapping? if (clazz.equals(ClassSelector.class)) { sel = ((ClassSelector) b).getClass(f); if (sel == null) { continue; } idMap = classIdMap.get(sel); } else { idMap = classIdMap.get(clazz); } if (sel != null && f.getType().equals(Long.TYPE)) { long oldKey = f.getLong(b); if (oldKey > 0) { int id = UIelement.extractHistIdFromComposedId(oldKey); if (idMap.get(id) != null) { long newKey = (oldKey & 0xffffffff00000000L) + idMap.get(id); f.setLong(b, newKey); } } } else { int oldKey = f.getInt(b); if (oldKey > 0) { if (c.getName().contains("CIimage")) { System.out.println(f.getName() + ":" + idMap.get(oldKey)); } f.setInt(b, idMap.get(oldKey)); } } } // re-attach detached binary data for (Field f : detached) { int index = f.getAnnotation(Detach.class).index(); String path = Export.createBinaryPath(index, b.getCID(), detachMap.get(b.getDBid())); f.set(b, readData(path)); } // set new historic ID b.setHistId(historicMap.get(b.getHistId())); if (c.equals(CIfile.class)) { ciFileHashSet.add(((CIfile) b).getDBfile()); } dao.update(b); // re-import DBfile data if (c.equals(DBfile.class)) { DBfile file = (DBfile) b; if (ciFileHashSet.contains(file.getHistId())) { // adapt CIfile virtual path: // /files/ciId/uiElementId/fileName String[] split = file.getPath().split("/"); split[2] = "" + classIdMap.get(CI.class).get(Integer.parseInt(split[2])); long composed = Long.parseLong(split[3]); int id = UIelement.extractHistIdFromComposedId(composed); HashMap<Integer, Integer> idMap = classIdMap .get(UIelement.getClassIdFromComposedId(composed)); split[3] = "" + ((composed & 0xffffffff00000000L) + idMap.get(id)); StringBuffer buf = new StringBuffer(); for (String s : split) { if (s.equals("")) { continue; } buf.append("/"); buf.append(s); } dBFilePathField.set(file, buf.toString()); } writeFile(dao, file, Export.FILES_DIR + fileIdMap.get(file.getDBid())); } dao.flush(); // try to free memory if (b instanceof CIblob) { // for EclipseLink a session clearing necessary! only // detaching isn't working really - // memory consumption is increasing in spite of detaching // objects! if (dao.isJPA() && dao.getJPAimpl() == DAO.JPA_IMPL.ECLIPSELINK) { dao.clear(); } else { dao.detach(b); } // clear binary data ((CIblob) b).resetBlob(); b = null; } } } }
From source file:alice.tuprolog.lib.OOLibrary.java
/** * get the value of the field/*from w w w . j av a2 s. c o m*/ */ private boolean java_get(PTerm objId, PTerm fieldTerm, PTerm what) { if (!fieldTerm.isAtom()) { return false; } String fieldName = ((Struct) fieldTerm).getName(); Object obj = null; try { Class<?> cl = null; if (objId.isCompound() && ((Struct) objId).getName().equals("class")) { String clName = null; if (((Struct) objId).getArity() == 1) clName = alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString()); if (clName != null) { try { cl = Class.forName(clName, true, dynamicLoader); } catch (ClassNotFoundException ex) { getEngine().logger.warn("Java class not found: " + clName); return false; } catch (Exception ex) { getEngine().logger.warn("Static field " + fieldName + " not found in class " + alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString())); return false; } } } else { String objName = alice.util.Tools.removeApices(objId.toString()); obj = currentObjects.get(objName); if (obj == null) { return false; } cl = obj.getClass(); } Field field = cl.getField(fieldName); Class<?> fc = field.getType(); field.setAccessible(true); if (fc.equals(Integer.TYPE) || fc.equals(Byte.TYPE)) { int value = field.getInt(obj); return unify(what, new alice.tuprolog.Int(value)); } else if (fc.equals(java.lang.Long.TYPE)) { long value = field.getLong(obj); return unify(what, new alice.tuprolog.Long(value)); } else if (fc.equals(java.lang.Float.TYPE)) { float value = field.getFloat(obj); return unify(what, new alice.tuprolog.Float(value)); } else if (fc.equals(java.lang.Double.TYPE)) { double value = field.getDouble(obj); return unify(what, new alice.tuprolog.Double(value)); } else { // the field value is an object Object res = field.get(obj); return bindDynamicObject(what, res); } } catch (NoSuchFieldException ex) { getEngine().logger.warn("Field " + fieldName + " not found in class " + objId); return false; } catch (Exception ex) { getEngine().logger.warn("Generic error in accessing the field"); return false; } }
From source file:com.cloudera.sqoop.SqoopOptions.java
/** * Return a Properties instance that encapsulates all the "sticky" * state of this SqoopOptions that should be written to a metastore * to restore the job later./* w w w .j a v a2 s .co m*/ */ public Properties writeProperties() { Properties props = new Properties(); try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { putProperty(props, propName, Integer.toString(f.getInt(this))); } else if (typ.equals(boolean.class)) { putProperty(props, propName, Boolean.toString(f.getBoolean(this))); } else if (typ.equals(long.class)) { putProperty(props, propName, Long.toString(f.getLong(this))); } else if (typ.equals(String.class)) { putProperty(props, propName, (String) f.get(this)); } else if (typ.equals(Integer.class)) { putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString()); } else if (typ.isEnum()) { putProperty(props, propName, f.get(this).toString()); } else { throw new RuntimeException("Could not set property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) { // If the user specifies, we may store the password in the metastore. putProperty(props, "db.password", this.password); putProperty(props, "db.require.password", "false"); } else if (this.password != null) { // Otherwise, if the user has set a password, we just record // a flag stating that the password will need to be reentered. putProperty(props, "db.require.password", "true"); } else { // No password saved or required. putProperty(props, "db.require.password", "false"); } putProperty(props, "db.column.list", arrayToList(this.columns)); setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); setArgArrayProperties(props, "tool.arguments", this.extraArgs); return props; }
From source file:com.cloudera.sqoop.SqoopOptions.java
@SuppressWarnings("unchecked") /**// ww w . ja va2 s.c o m * Given a set of properties, load this into the current SqoopOptions * instance. */ public void loadProperties(Properties props) { try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.equals(Integer.class)) { String value = props.getProperty(propName, f.get(this) == null ? "null" : f.get(this).toString()); f.set(this, value.equals("null") ? null : new Integer(value)); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; }
From source file:org.apache.sqoop.SqoopOptions.java
/** * Return a Properties instance that encapsulates all the "sticky" * state of this SqoopOptions that should be written to a metastore * to restore the job later.//w ww.ja v a 2 s .co m */ public Properties writeProperties() { Properties props = new Properties(); try { Field[] fields = SqoopOptions.class.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { putProperty(props, propName, Integer.toString(f.getInt(this))); } else if (typ.equals(boolean.class)) { putProperty(props, propName, Boolean.toString(f.getBoolean(this))); } else if (typ.equals(long.class)) { putProperty(props, propName, Long.toString(f.getLong(this))); } else if (typ.equals(String.class)) { putProperty(props, propName, (String) f.get(this)); } else if (typ.equals(Integer.class)) { putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString()); } else if (typ.isEnum()) { putProperty(props, propName, f.get(this).toString()); } else { throw new RuntimeException("Could not set property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) { // If the user specifies, we may store the password in the metastore. putProperty(props, "db.password", this.password); putProperty(props, "db.require.password", "false"); } else if (this.password != null) { // Otherwise, if the user has set a password, we just record // a flag stating that the password will need to be reentered. putProperty(props, "db.require.password", "true"); } else { // No password saved or required. putProperty(props, "db.require.password", "false"); } putProperty(props, "db.column.list", arrayToList(this.columns)); setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); setArgArrayProperties(props, "tool.arguments", this.extraArgs); setPropertiesAsNestedProperties(props, "db.connect.params", this.connectionParams); setPropertiesAsNestedProperties(props, "map.column.hive", this.mapColumnHive); setPropertiesAsNestedProperties(props, "map.column.java", this.mapColumnJava); return props; }
From source file:org.apache.sqoop.SqoopOptions.java
@SuppressWarnings("unchecked") /**//from w ww. j av a 2s . c o m * Given a set of properties, load this into the current SqoopOptions * instance. */ public void loadProperties(Properties props) { try { Field[] fields = SqoopOptions.class.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.equals(Integer.class)) { String value = props.getProperty(propName, f.get(this) == null ? "null" : f.get(this).toString()); f.set(this, value.equals("null") ? null : new Integer(value)); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); this.connectionParams = getPropertiesAsNetstedProperties(props, "db.connect.params"); // Loading user mapping this.mapColumnHive = getPropertiesAsNetstedProperties(props, "map.column.hive"); this.mapColumnJava = getPropertiesAsNetstedProperties(props, "map.column.java"); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; // If we loaded true verbose flag, we need to apply it if (this.verbose) { LoggingUtils.setDebugLevel(); } // Custom configuration options this.invalidIdentifierPrefix = props.getProperty("invalid.identifier.prefix", "_"); }
From source file:org.rzo.yajsw.os.ms.win.w32.WindowsXPProcess.java
/** * Writefd./*from w ww. ja v a2s .com*/ * * @param fd * the fd * @param pointer * the pointer */ private void writefd(FileDescriptor fd, Pointer pointer) { try { // Field[] fields = FileDescriptor.class.getDeclaredFields(); // System.out.println("fields"); // for (Field field : fields){ // System.out.println(field.getName()); // } // System.out.println("writefd"); Field handleField = FileDescriptor.class.getDeclaredField("handle"); handleField.setAccessible(true); Field peerField = Pointer.class.getDeclaredField("peer"); peerField.setAccessible(true); long value = peerField.getLong(pointer); // System.out.println(value); // System.out.flush(); handleField.setLong(fd, value); } catch (Exception e) { e.printStackTrace(); } }