/** * オブジェクトのフィールドにデータを設定する<br> * Integer、Float、Float[]、Stringにしか対応していない * * @param obj 設定対象オブジェクト * @param fl 設定対象フィールド * @param ty 設定対象フィールドの型 * @param data 設定データ * @throws IllegalArgumentException * @throws IllegalAccessException */ protected void dataSetter(Object obj, Field fl, Class ty, String data) throws IllegalArgumentException, IllegalAccessException { // Integer型のデータを設定 if (ty.toString().equals("class java.lang.Integer")) { fl.set(obj, Integer.parseInt(data)); } // Float型のデータを設定 if (ty.toString().equals("class java.lang.Float")) { fl.set(obj, Float.parseFloat(data)); } // String型のデータを設定(""の内側) if (ty.toString().equals("class java.lang.String")) { fl.set(obj, getDoubleQuoatString(data)); } // Float[]型のデータを設定 if (ty.toString().equals("class [Ljava.lang.Float;")) { String[] s; s = data.split(" "); Float[] f = new Float[s.length]; for (int i = 0; i < s.length; i++) { f[i] = Float.parseFloat(s[i]); } fl.set(obj, f); } }
/** * Computes the serial version UID value for the given class. The code is taken from {@link * ObjectStreamClass#computeDefaultSUID(Class)}. * * @param cls A class. * @return A serial version UID. * @throws IOException If failed. */ static long computeSerialVersionUid(Class cls) throws IOException { if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) { return ObjectStreamClass.lookup(cls).getSerialVersionUID(); } MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new IOException("Failed to get digest for SHA.", e); } md.update(cls.getName().getBytes(UTF_8)); for (Field f : getFieldsForSerialization(cls)) { md.update(f.getName().getBytes(UTF_8)); md.update(f.getType().getName().getBytes(UTF_8)); } byte[] hashBytes = md.digest(); long hash = 0; // Composes a single-long hash from the byte[] hash. for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) hash = (hash << 8) | (hashBytes[i] & 0xFF); return hash; }
public static Document Document(File f) throws IOException, InterruptedException { // make a new, empty document Document doc = new Document(); // Add the url as a field named "url". Use an UnIndexed field, so // that the url is just stored with the document, but is not searchable. doc.add(Field.UnIndexed("url", f.getPath().replace(dirSep, '/'))); // Add the last modified date of the file a field named "modified". Use a // Keyword field, so that it's searchable, but so that no attempt is made // to tokenize the field into words. doc.add(Field.Keyword("modified", DateField.timeToString(f.lastModified()))); // Add the uid as a field, so that index can be incrementally maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", uid(f), false, true, false)); HTMLParser parser = new HTMLParser(f); // Add the tag-stripped contents as a Reader-valued Text field so it will // get tokenized and indexed. doc.add(Field.Text("contents", parser.getReader())); // Add the summary as an UnIndexed field, so that it is stored and returned // with hit documents for display. doc.add(Field.UnIndexed("summary", parser.getSummary())); // Add the title as a separate Text field, so that it can be searched // separately. doc.add(Field.Text("title", parser.getTitle())); // return the document return doc; }
/** * Generates a byte array representing the contents of this page. Used to serialize this page to * disk. * * <p>The invariant here is that it should be possible to pass the byte array generated by * getPageData to the HeapPage constructor and have it produce an identical HeapPage object. * * @see #HeapPage * @return A byte array correspond to the bytes of this page. */ public byte[] getPageData() { // int len = header.length*4 + BufferPool.PAGE_SIZE; int len = BufferPool.PAGE_SIZE; ByteArrayOutputStream baos = new ByteArrayOutputStream(len); DataOutputStream dos = new DataOutputStream(baos); // create the header of the page try { dos.write(header.getHeader()); } catch (IOException e) { // this really shouldn't happen e.printStackTrace(); } // create the tuples for (int i = 0; i < numSlots; i++) { // empty slot if (!getSlot(i)) { for (int j = 0; j < td.getSize(); j++) { try { dos.writeByte(0); } catch (IOException e) { e.printStackTrace(); } } continue; } // non-empty slot for (int j = 0; j < td.numFields(); j++) { Field f = tuples[i].getField(j); try { f.serialize(dos); } catch (IOException e) { e.printStackTrace(); } } } // padding int zerolen = BufferPool.PAGE_SIZE - numSlots * td.getSize() - header.length(); byte[] zeroes = new byte[zerolen]; try { dos.write(zeroes, 0, zerolen); } catch (IOException e) { e.printStackTrace(); } try { dos.flush(); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); }
private String field(Issue issue, TicketFields filed) { Field field = issue.getFieldByName(filed.getName()); if (field != null) { Object fieldValue = field.getValue(); if (fieldValue != null) { return fieldValue.toString(); } } return ""; }
@SuppressWarnings("unchecked") private void addFields(List list, boolean isStatic) { int count = klass.getFieldCount(isStatic); for (int i = 0; i != count; ++i) { Field field = klass.getField(i, isStatic); FieldID fid = new FieldID(JDWP.getTag(field.getType()), field.getOffset(), isStatic, getID()); ProxyField proxyField = new ProxyField(fid, field); list.add(proxyField); } }
// Use reflection to get version since early versions // of ImageJ do not have the IJ.getVersion() method. String version() { String version = ""; try { Class ijClass = ImageJ.class; Field field = ijClass.getField("VERSION"); version = (String) field.get(ijClass); } catch (Exception ex) { } return version; }
/** * `获取给定对象的属性的值` `@param fieldName 属性名` `@param obj 对象` * * @return */ public static Object getFieldValue(String fieldName, Object obj) { try { Class cls = obj.getClass(); Field field = cls.getDeclaredField(fieldName); return field.get(obj); } catch (Exception e) { e.printStackTrace(); print("Field access error!"); throw new RuntimeException(e); } }
@Override public Map parse() { if (field.getType().compareTo("json") == 0 // if the signature is *-> * then guess using { || field.getType().startsWith("{")) { if (jsonObject instanceof String) { logger.debug("json object is string " + jsonObject); return null; } else return (Map) jsonObject; } else return null; }
/** * Set the current opcode. This sets four global fields: the currentOpcode, the * currentOpcodeArgTable, the currentFormat and the currentOpcodeSymbolicNames. * * @param opcode The IA32 architecture opcode to make the current opcode */ static void setCurrentOpcode(String opcode) { try { currentOpcode = opcode; currentOpcodeArgTable = (int[]) opcodeArgTables.get(opcode); currentFormat = OperatorFormatTables.getFormat(opcode); Field f = formats.getDeclaredField(currentFormat + "ParameterNames"); currentOpcodeSymbolicNames = (String[]) f.get(null); } catch (Throwable e) { throw new Error("Cannot handle Assembler opcode " + opcode, e); } }
private Field findSqlMapExecutorDelegate(SqlMapClient sqlMapClient) { Class<?> searchType = sqlMapClient.getClass(); while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); for (Field field : fields) { if (SqlMapExecutorDelegate.class.isAssignableFrom(field.getType())) return field; } searchType = searchType.getSuperclass(); } return null; }
public static Properties getParent(Properties p) { try { Field f = Properties.class.getDeclaredField("defaults"); f.setAccessible(true); return (Properties) f.get(p); } catch (Exception e) { Field[] fields = Properties.class.getFields(); System.err.println(Arrays.toString(fields)); return null; } }
public SqlJsonImplementation(Object jsonObject, Field field) { this.jsonObject = jsonObject; if (jsonObject instanceof String) field.setType("string"); else if (jsonObject instanceof Number) field.setType("number"); else if (jsonObject instanceof Boolean) field.setType("boolean"); else if (jsonObject instanceof List) field.setType("array"); // map should be json as well else field.setType("json"); this.field = field; }
/** Constructor, initializing the default options. */ protected AProp() { try { for (final Field f : getClass().getFields()) { final Object obj = f.get(null); if (!(obj instanceof Object[])) continue; final Object[] arr = (Object[]) obj; props.put(arr[0].toString(), arr[1]); } } catch (final Exception ex) { Util.notexpected(ex); } }
public IdentitySchema(Configuration configuration) { this.configuration = configuration; this.properties = configuration.getProperties(); this.dialect = Dialect.getDialect(properties); try { // get the mapping field via reflection :-( Field mappingField = Configuration.class.getDeclaredField("mapping"); mappingField.setAccessible(true); this.mapping = (Mapping) mappingField.get(configuration); } catch (Exception e) { throw new RuntimeException("couldn't get the hibernate mapping", e); } }
private static LinkedHashMap<String, Prop> createProps() { Field[] fs = Configuration.class.getDeclaredFields(); LinkedHashMap<String, Prop> res = new LinkedHashMap<String, Prop>(); for (Field f : fs) if (!Modifier.isStatic(f.getModifiers())) { Description annotation = f.getAnnotation(Description.class); if (annotation != null) { String name = f.getName().replace('_', '.'); res.put(name, new Prop(name, annotation.value(), f)); } } return res; }
/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
public Object getUIRep() { if (uiRepCopy == null) { if (field == null) ExpCoordinator.print( new String("FieldParam(" + getLabel() + ").getUIRep field is null"), TEST_UIREP); else ExpCoordinator.print( new String("FieldParam(" + getLabel() + ").getUIRep field:" + field.toString()), TEST_UIREP); uiRepCopy = field.getUIRepCopy(isEditable()); setUIRep(uiRepCopy.getComponent()); } return (super.getUIRep()); }
// generates the 'select' part of the SQL select statement public String selectProperties(DataObj d) { StringBuilder s = new StringBuilder(1024); String name = d.getName(); s.append("select "); boolean firstField = true; for (Field f : d.getFields()) { if (firstField) { firstField = false; s.append(name + "." + f.getName() + " "); } else { s.append(", " + name + "." + f.getName() + " "); } } return s.toString(); }
@Override public String getString() throws SQLException { int type = JSONTypes.jsonTypes.get(field.getType()); switch (type) { case JSONTypes.JSON_ARRAY: case JSONTypes.JSON_OBJECT: case JSONTypes.JSON_MAP: toJson(); return sqlJson; case JSONTypes.JSON_NULL: return null; case JSONTypes.JSON_STRING: if (sqlJson != null) return sqlJson; if (jsonObject != null) return (String) jsonObject; isNull = true; return null; // let the default implementation of toString figure it out case JSONTypes.JSON_BOOLEAN: case JSONTypes.JSON_NUMBER: return jsonObject.toString(); default: return ""; } }
/** * Delegates to {@link Field#set(Object,Object)} hiding IllegalAccessException. * * @param f A field. * @param obj An object. * @param val A value. * @throws IOException If failed. */ static void set(Field f, Object obj, Object val) throws IOException { try { f.set(obj, val); } catch (IllegalAccessException e) { throw new IOException("Failed to set field value: " + f, e); } }
/** * Delegates to {@link Field#get(Object)} hiding IllegalAccessException. * * @param f A field. * @param obj An object. * @return The value of the represented field in object. * @throws IOException If failed. */ static Object get(Field f, Object obj) throws IOException { try { return f.get(obj); } catch (IllegalAccessException e) { throw new IOException("Failed to get field value: " + f, e); } }
public SqlMapRepositoryFactory(SqlMapClient sqlMapClient) { Assert.notNull(sqlMapClient, "SqlMapClient must not be null!"); this.sqlMapClient = (SqlMapClientImpl) sqlMapClient; this.sqlMapClientTemplate = new SqlMapClientTemplate(sqlMapClient); if (ExtendedSqlMapClient.class.isAssignableFrom(sqlMapClient.getClass())) { this.sqlMapExecutorDelegate = ((ExtendedSqlMapClient) sqlMapClient).getDelegate(); } else if (hasSqlMapExecutorDelegate(sqlMapClient)) { Field field = findSqlMapExecutorDelegate(sqlMapClient); field.setAccessible(true); this.sqlMapExecutorDelegate = (SqlMapExecutorDelegate) ReflectionUtils.getField(field, sqlMapClient); } else { throw new IllegalArgumentException("not found SqlMapExecutorDelegate in SqlMapClient."); } }
private MutableTreeNode populateAttributes(CavityDBObject obj) { DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs"); Class cls = obj.getClass(); for (Field f : cls.getFields()) { int mod = f.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { String fieldName = f.getName(); try { Object value = f.get(obj); tree.add( new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value)))); } catch (IllegalAccessException e) { // do nothing. } } } return tree; }
public void checki(boolean basic, Var x, Field f, Var y, Field g) { fail = false; if (!basic) { if (x.getType().getKind() == TypeIR.Kind.VOID) fail = true; if (y.getType().getKind() == TypeIR.Kind.VOID) fail = true; if (fail) { assert (false); } } assertion(basic, x, f); assertion(basic, y, g); if (fail) { assert (false); System.out.println(" Overall ! "); System.out.println(x.getType()); if (f != null) System.out.println(" f " + f.getType()); System.out.println(y.getType()); if (g != null) System.out.println(" g " + g.getType()); } }
private static void linkChildren(RArray parentRealView, ViewTrace parentTrace) { Class viewClass = parentRealView.getClass(); Field[] fields = getAllFields(viewClass); for (Field f : fields) { if (f.isSynthetic()) { continue; } Class fieldClass = f.getType(); if (RArray.class.isAssignableFrom(fieldClass)) { try { f.setAccessible(true); Object o = f.get(parentRealView); if (o instanceof TracingView) { ((TracingView) o).getTrace().parentView = parentTrace; } } catch (IllegalAccessException e) { assert Utils.check(false, "can't read a view field " + e); } } } }
protected void generateView(Map<String, org.ektorp.support.DesignDocument.View> views, Field f) { DocumentReferences referenceMetaData = f.getAnnotation(DocumentReferences.class); if (referenceMetaData == null) { LOG.warn("No DocumentReferences annotation found in field: ", f.getName()); return; } if (referenceMetaData.view().length() > 0) { LOG.debug("Skipping view generation for field {} as view is already specified", f.getName()); return; } if (Set.class.isAssignableFrom(f.getType())) { generateSetBasedDocRefView(views, f, referenceMetaData); } else { throw new ViewGenerationException( String.format( "The type of the field: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)", f.getName(), f.getDeclaringClass())); } }
private void dump( OutputSink out, ObjectReference obj, ReferenceType refType, ReferenceType refTypeBase) { for (Field field : refType.fields()) { out.print(" "); if (!refType.equals(refTypeBase)) { out.print(refType.name() + "."); } out.print(field.name() + ": "); Object o = obj.getValue(field); out.println((o == null) ? "null" : o.toString()); // Bug ID 4374471 } if (refType instanceof ClassType) { ClassType sup = ((ClassType) refType).superclass(); if (sup != null) { dump(out, obj, sup, refTypeBase); } } else if (refType instanceof InterfaceType) { for (InterfaceType sup : ((InterfaceType) refType).superinterfaces()) { dump(out, obj, sup, refTypeBase); } } }
/** Find field in direct superinterfaces. */ public Field findInterfaceField(Symbol name, Symbol sig) { ObjArray interfaces = getLocalInterfaces(); int n = (int) interfaces.getLength(); for (int i = 0; i < n; i++) { InstanceKlass intf1 = (InstanceKlass) interfaces.getObjAt(i); if (Assert.ASSERTS_ENABLED) { Assert.that(intf1.isInterface(), "just checking type"); } // search for field in current interface Field f = intf1.findLocalField(name, sig); if (f != null) { if (Assert.ASSERTS_ENABLED) { Assert.that(f.getAccessFlagsObj().isStatic(), "interface field must be static"); } return f; } // search for field in direct superinterfaces f = intf1.findInterfaceField(name, sig); if (f != null) return f; } // otherwise field lookup fails return null; }
/** Reflect operations demo */ public static void reflect(Object obj) { // `cls用于描述对象所属的类` Class cls = obj.getClass(); print("Class Name: " + cls.getCanonicalName()); // `fields包含对象的所有属性` Field[] fields = cls.getDeclaredFields(); print("List of fields:"); for (Field f : fields) { print(String.format("%30s %15s", f.getType(), f.getName())); } // `methods包含对象的所有方法` Method[] methods = cls.getDeclaredMethods(); print("List of methods:"); for (Method m : methods) print( String.format( "%30s %15s %30s", m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes()))); Constructor[] constructors = cls.getConstructors(); print("List of contructors:"); for (Constructor c : constructors) print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes()))); }