private int findfd(Object fdObj) throws Exception { Class cl; Field f; Object val, implVal; if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) { cl = fdObj.getClass(); f = cl.getDeclaredField("impl"); f.setAccessible(true); val = f.get(fdObj); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); implVal = f.get(val); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(implVal)).intValue(); } else if (fdObj instanceof java.io.FileDescriptor) { cl = fdObj.getClass(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(fdObj)).intValue(); } else { throw new IllegalArgumentException("Illegal Object type."); } }
/** * 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); } }
/** * 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; }
// 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); } }
/** * 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); } }
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; } }
/** 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 void netxsurgery() throws Exception { /* Force off NetX codebase classloading. */ Class<?> nxc; try { nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e1) { try { nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e2) { throw (new Exception("No known NetX on classpath")); } } ClassLoader cl = MainFrame.class.getClassLoader(); if (!nxc.isInstance(cl)) { throw (new Exception("Not running from a NetX classloader")); } Field cblf, lf; try { cblf = nxc.getDeclaredField("codeBaseLoader"); lf = nxc.getDeclaredField("loaders"); } catch (NoSuchFieldException e) { throw (new Exception("JNLPClassLoader does not conform to its known structure")); } cblf.setAccessible(true); lf.setAccessible(true); Set<Object> loaders = new HashSet<Object>(); Stack<Object> open = new Stack<Object>(); open.push(cl); while (!open.empty()) { Object cur = open.pop(); if (loaders.contains(cur)) continue; loaders.add(cur); Object curl; try { curl = lf.get(cur); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } for (int i = 0; i < Array.getLength(curl); i++) { Object other = Array.get(curl, i); if (nxc.isInstance(other)) open.push(other); } } for (Object cur : loaders) { try { cblf.set(cur, null); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } } }
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; }
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); } } } }
private static void extractViewPattern(int depth, ViewTrace trace, StringBuilder p) { if (!processedViewsForPatterns.add(trace)) { p.append("(ALIASED) "); } p.append(trace.realView.getClass() + " size = " + trace.realView.size() + "\n"); indent(depth, p); p.append(" use:"); if (trace.materializeCount == 0 && trace.sumCount == 0 && trace.getCount == 0) { p.append(" UNUSED"); } else { if (trace.getCount > 0) { p.append(" get"); } if (trace.materializeCount > 0) { p.append(" materialize"); } if (trace.sumCount > 0) { p.append(" sum"); } } p.append("\n"); if (false) { p.append(" allocationSite ="); Site.printSite(trace.allocationSite, p); p.append("\n"); indent(depth, p); } RArray view = trace.realView; Class viewClass = view.getClass(); Field[] fields = getAllFields(viewClass); boolean printedField = false; for (Field f : fields) { if (f.isSynthetic()) { continue; } Class fieldClass = f.getType(); if (RArray.class.isAssignableFrom(fieldClass)) { continue; // these later } indent(depth, p); p.append(" " + f.getName() + " "); try { f.setAccessible(true); Object o = f.get(view); p.append(o == null ? "null (" + fieldClass + ")" : o.getClass()); p.append("\n"); printedField = true; } catch (IllegalAccessException e) { assert Utils.check(false, "can't read a view field " + e); } } boolean printNewline = printedField; for (Field f : fields) { if (f.isSynthetic()) { continue; } Class fieldClass = f.getType(); if (!RArray.class.isAssignableFrom(fieldClass)) { continue; } if (printNewline) { p.append("\n"); printNewline = false; } indent(depth, p); p.append(" " + f.getName() + " "); try { f.setAccessible(true); Object o = f.get(view); if (o instanceof TracingView) { p.append("VIEW "); TracingView child = (TracingView) o; extractViewPattern(depth + 2, child.getTrace(), p); } else { p.append("ARRAY " + o.getClass() + " size = " + ((RArray) o).size()); if (o instanceof View) { ps.println("MISSED VIEW " + o); } } p.append("\n"); } catch (IllegalAccessException e) { assert Utils.check(false, "can't read a view field " + e); } } }
/** * Reads the configuration file and initializes the project properties. The file is located in the * project home directory. * * @param prop property file extension */ protected synchronized void read(final String prop) { file = new IOFile(HOME + IO.BASEXSUFFIX + prop); final StringList read = new StringList(); final TokenBuilder err = new TokenBuilder(); if (!file.exists()) { err.addExt("Saving properties in \"%\"..." + NL, file); } else { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file.file())); for (String line; (line = br.readLine()) != null; ) { line = line.trim(); if (line.isEmpty() || line.charAt(0) == '#') continue; final int d = line.indexOf('='); if (d < 0) { err.addExt("%: \"%\" ignored. " + NL, file, line); continue; } final String val = line.substring(d + 1).trim(); String key = line.substring(0, d).trim(); // extract numeric value in key int num = 0; final int ss = key.length(); for (int s = 0; s < ss; ++s) { if (Character.isDigit(key.charAt(s))) { num = Integer.parseInt(key.substring(s)); key = key.substring(0, s); break; } } read.add(key); final Object entry = props.get(key); if (entry == null) { err.addExt("%: \"%\" not found. " + NL, file, key); } else if (entry instanceof String) { props.put(key, val); } else if (entry instanceof Integer) { props.put(key, Integer.parseInt(val)); } else if (entry instanceof Boolean) { props.put(key, Boolean.parseBoolean(val)); } else if (entry instanceof String[]) { if (num == 0) { props.put(key, new String[Integer.parseInt(val)]); } else { ((String[]) entry)[num - 1] = val; } } else if (entry instanceof int[]) { ((int[]) entry)[num] = Integer.parseInt(val); } } } catch (final Exception ex) { err.addExt("% could not be parsed." + NL, file); Util.debug(ex); } finally { if (br != null) try { br.close(); } catch (final IOException ex) { } } } // check if all mandatory files have been read try { if (err.isEmpty()) { boolean ok = true; for (final Field f : getClass().getFields()) { final Object obj = f.get(null); if (!(obj instanceof Object[])) continue; final String key = ((Object[]) obj)[0].toString(); ok &= read.contains(key); } if (!ok) err.addExt("Saving properties in \"%\"..." + NL, file); } } catch (final IllegalAccessException ex) { Util.notexpected(ex); } if (!err.isEmpty()) { Util.err(err.toString()); write(); } }
public TypeUniverse() { Providers providers = Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend().getProviders(); metaAccess = providers.getMetaAccess(); constantReflection = providers.getConstantReflection(); snippetReflection = Graal.getRequiredCapability(SnippetReflectionProvider.class); Unsafe theUnsafe = null; try { theUnsafe = Unsafe.getUnsafe(); } catch (Exception e) { try { Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeField.setAccessible(true); theUnsafe = (Unsafe) theUnsafeField.get(null); } catch (Exception e1) { throw (InternalError) new InternalError("unable to initialize unsafe").initCause(e1); } } unsafe = theUnsafe; Class<?>[] initialClasses = { void.class, boolean.class, byte.class, short.class, char.class, int.class, float.class, long.class, double.class, Object.class, Class.class, ClassLoader.class, String.class, Serializable.class, Cloneable.class, Test.class, TestMetaAccessProvider.class, List.class, Collection.class, Map.class, Queue.class, HashMap.class, LinkedHashMap.class, IdentityHashMap.class, AbstractCollection.class, AbstractList.class, ArrayList.class }; for (Class<?> c : initialClasses) { addClass(c); } for (Field f : Constant.class.getDeclaredFields()) { int mods = f.getModifiers(); if (f.getType() == Constant.class && Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) { try { Constant c = (Constant) f.get(null); if (c != null) { constants.add(c); } } catch (Exception e) { } } } for (Class<?> c : classes) { if (c != void.class && !c.isArray()) { constants.add(snippetReflection.forObject(Array.newInstance(c, 42))); } } constants.add(snippetReflection.forObject(new ArrayList<>())); constants.add(snippetReflection.forObject(new IdentityHashMap<>())); constants.add(snippetReflection.forObject(new LinkedHashMap<>())); constants.add(snippetReflection.forObject(new TreeMap<>())); constants.add(snippetReflection.forObject(new ArrayDeque<>())); constants.add(snippetReflection.forObject(new LinkedList<>())); constants.add(snippetReflection.forObject("a string")); constants.add(snippetReflection.forObject(42)); constants.add(snippetReflection.forObject(String.class)); constants.add(snippetReflection.forObject(String[].class)); }
private void dump() throws IOException { lookupMethod = null; try { lookupMethod = catalog.getClass().getMethod("lookup", new Class[] {java.lang.String.class}); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } Method pluralMethod = null; try { pluralMethod = catalog.getClass().getMethod("get_msgid_plural_table", new Class[0]); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } Field pluralField = null; try { pluralField = catalog.getClass().getField("plural"); } catch (NoSuchFieldException e) { } catch (SecurityException e) { } // Search for the header entry. { Object header_entry = null; Enumeration keys = catalog.getKeys(); while (keys.hasMoreElements()) if ("".equals(keys.nextElement())) { header_entry = lookup(""); break; } // If there is no header entry, fake one. // FIXME: This is not needed; right after po_lex_charset_init set // the PO charset to UTF-8. if (header_entry == null) header_entry = "Content-Type: text/plain; charset=UTF-8\n"; dumpMessage("", null, header_entry); } // Now the other messages. { Enumeration keys = catalog.getKeys(); Object plural = null; if (pluralMethod != null) { // msgfmt versions > 0.13.1 create a static get_msgid_plural_table() // method. try { plural = pluralMethod.invoke(catalog, new Object[0]); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } } else if (pluralField != null) { // msgfmt versions <= 0.13.1 create a static plural field. try { plural = pluralField.get(catalog); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (plural instanceof String[]) { // A GNU gettext created class with plural handling, Java2 format. int i = 0; while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); Object value = lookup(key); String key_plural = (value instanceof String[] ? ((String[]) plural)[i++] : null); if (!"".equals(key)) dumpMessage(key, key_plural, value); } if (i != ((String[]) plural).length) throw new RuntimeException("wrong plural field length"); } else if (plural instanceof Hashtable) { // A GNU gettext created class with plural handling, Java format. while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); if (!"".equals(key)) { Object value = lookup(key); String key_plural = (value instanceof String[] ? (String) ((Hashtable) plural).get(key) : null); dumpMessage(key, key_plural, value); } } } else if (plural == null) { // No plural handling. while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); if (!"".equals(key)) dumpMessage(key, null, lookup(key)); } } else throw new RuntimeException("wrong plural field value"); } }
private static void dumpView(int depth, ViewTrace trace) { printedIndividualViews.add(trace); ps.println(trace.realView + " size = " + trace.realView.size()); if (TRACE_ALLOCATION_SITE) { indent(depth); ps.print(" allocationSite ="); Site.printSite(trace.allocationSite); ps.println(); } int unused = trace.unusedElements(); int redundant = trace.redundantGets(); boolean singleUse; Site[] useSites; if (TRACE_USE_SITES) { useSites = trace.useSites.toArray(new Site[trace.useSites.size()]); singleUse = (useSites.length == 1); } else if (TRACE_SINGLE_USE_SITE) { useSites = null; singleUse = !trace.multipleUseSites; } else { useSites = null; singleUse = false; } if (singleUse) { indent(depth); ps.print(" singleUseSite = US"); Site.printSite(useSites != null ? useSites[0] : trace.singleUseSite); if (trace.getCount > 0) { ps.println(" (get)"); } else if (trace.sumCount > 0) { ps.println(" (sum)"); } else { ps.println(" (materialize)"); } } else if (trace.getCount > 0) { if (TRACE_FIRST_GET_SITE) { indent(depth); ps.print(" firstGetSite ="); Site.printSite(trace.firstGetSite); ps.println(); } if (trace.materializeCount == 0 && trace.sumCount == 0) { if (unused > 0) { indent(depth); ps.println(" unusedElements = " + unused); } if (redundant > 0) { indent(depth); ps.println(" redundantGets = " + redundant + " (no materialize, sum)"); } } } else { if (trace.materializeCount == 0 && trace.sumCount == 0) { indent(depth); ps.println(" UNUSED"); } else { indent(depth); ps.println( " materializeCount = " + trace.materializeCount + " sumCount = " + trace.sumCount + " getCount = " + trace.getCount); } } if (TRACE_FIRST_MATERIALIZE_SITE && trace.materializeCount > 0 && !singleUse) { indent(depth); ps.print(" firstMaterializeSite ="); Site.printSite(trace.firstMaterializeSite); ps.println(); } if (TRACE_FIRST_SUM_SITE && trace.sumCount > 0 && !singleUse) { indent(depth); ps.print(" firstSumSite ="); Site.printSite(trace.firstSumSite); ps.println(); } if (TRACE_USE_SITES) { if (useSites.length != 1) { indent(depth); ps.println(" useSites (" + useSites.length + "):"); for (Site s : useSites) { indent(depth); ps.print(" US"); Site.printSite(s); ps.println(); } } } ps.println(); RArray view = trace.realView; Class viewClass = view.getClass(); Field[] fields = getAllFields(viewClass); boolean printedField = false; for (Field f : fields) { if (f.isSynthetic()) { continue; } Class fieldClass = f.getType(); if (RArray.class.isAssignableFrom(fieldClass)) { continue; // these later } indent(depth); ps.print(" " + f.getName() + " "); try { f.setAccessible(true); ps.println(f.get(view)); printedField = true; } catch (IllegalAccessException e) { assert Utils.check(false, "can't read a view field " + e); } } boolean printNewline = printedField; for (Field f : fields) { if (f.isSynthetic()) { continue; } Class fieldClass = f.getType(); if (!RArray.class.isAssignableFrom(fieldClass)) { continue; } if (printNewline) { ps.println(); printNewline = false; } indent(depth); ps.print(" " + f.getName() + " "); try { f.setAccessible(true); Object o = f.get(view); if (o instanceof TracingView) { ps.print("VIEW "); TracingView child = (TracingView) o; dumpView(depth + 2, child.getTrace()); } else { ps.print("ARRAY " + o + " size = " + ((RArray) o).size()); if (o instanceof View) { ps.println("MISSED VIEW " + o); } } ps.println(); } catch (IllegalAccessException e) { assert Utils.check(false, "can't read a view field " + e); } } }
public static Object getAdapterSelf(Class<?> adapterClass, Object adapter) throws NoSuchFieldException, IllegalAccessException { Field self = adapterClass.getDeclaredField("self"); return self.get(adapter); }
/** Writes the properties to disk. */ public final synchronized void write() { final StringBuilder user = new StringBuilder(); BufferedReader br = null; try { // caches options specified by the user if (file.exists()) { br = new BufferedReader(new FileReader(file.file())); for (String line; (line = br.readLine()) != null; ) { if (line.equals(PROPUSER)) break; } for (String line; (line = br.readLine()) != null; ) { user.append(line).append(NL); } } } catch (final Exception ex) { Util.debug(ex); } finally { if (br != null) try { br.close(); } catch (final IOException e) { } } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(file.file())); bw.write(PROPHEADER + NL); for (final Field f : getClass().getFields()) { final Object obj = f.get(null); if (!(obj instanceof Object[])) continue; final String key = ((Object[]) obj)[0].toString(); final Object val = props.get(key); if (val instanceof String[]) { final String[] str = (String[]) val; bw.write(key + " = " + str.length + NL); final int is = str.length; for (int i = 0; i < is; ++i) { if (str[i] != null) bw.write(key + (i + 1) + " = " + str[i] + NL); } } else if (val instanceof int[]) { final int[] num = (int[]) val; final int ns = num.length; for (int i = 0; i < ns; ++i) { bw.write(key + i + " = " + num[i] + NL); } } else { bw.write(key + " = " + val + NL); } } bw.write(NL + PROPUSER + NL); bw.write(user.toString()); } catch (final Exception ex) { Util.errln("% could not be written.", file); Util.debug(ex); } finally { if (bw != null) try { bw.close(); } catch (final IOException e) { } } }