/** * Returns a {@link Font} based on its name, height and style. Windows-specific strikeout and * underline flags are also supported. * * @param name the name of the font * @param size the size of the font * @param style the style of the font * @param strikeout the strikeout flag (warning: Windows only) * @param underline the underline flag (warning: Windows only) * @return {@link Font} The font matching the name, height, style, strikeout and underline */ public static Font getFont( String name, int size, int style, boolean strikeout, boolean underline) { String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline; Font font = m_fontMap.get(fontName); if (font == null) { FontData fontData = new FontData(name, size, style); if (strikeout || underline) { try { Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); // $NON-NLS-1$ Object logFont = FontData.class.getField("data").get(fontData); // $NON-NLS-1$ if (logFont != null && logFontClass != null) { if (strikeout) { logFontClass .getField("lfStrikeOut") .set(logFont, Byte.valueOf((byte) 1)); // $NON-NLS-1$ } if (underline) { logFontClass .getField("lfUnderline") .set(logFont, Byte.valueOf((byte) 1)); // $NON-NLS-1$ } } } catch (Throwable e) { System.err.println( "Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$ } } font = new Font(Display.getCurrent(), fontData); m_fontMap.put(fontName, font); } return font; }
static { if (!Boolean.getBoolean(GridSystemProperties.GG_JETTY_LOG_NO_OVERRIDE)) { String ctgrJetty = "org.eclipse.jetty"; // WARN for this category. String ctgrJettyUtil = "org.eclipse.jetty.util.log"; // ERROR for this... String ctgrJettyUtilComp = "org.eclipse.jetty.util.component"; // ...and this. try { Class<?> logCls = Class.forName("org.apache.log4j.Logger"); Object logJetty = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJetty); Object logJettyUtil = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtil); Object logJettyUtilComp = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtilComp); Class<?> lvlCls = Class.forName("org.apache.log4j.Level"); Object warnLvl = lvlCls.getField("WARN").get(null); Object errLvl = lvlCls.getField("ERROR").get(null); logJetty.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, warnLvl); logJettyUtil.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl); logJettyUtilComp.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl); } catch (Exception ignored) { // No-op. } } }
String getClassForParameter(String object, String field, boolean type) { for (KVP def : comps.entries) { if (object.equals(def.getKey())) { String clname = def.getValue().toString(); clname = getComponentClassName(clname); Class c; try { c = getClassLoader().loadClass(clname); } catch (ClassNotFoundException ex) { throw new ComponentException("Class not found: '" + clname + "'"); } try { if (type) { String canName = c.getField(field).getType().getCanonicalName(); if (canName == null) { throw new ComponentException("No canonical type name for : " + field); } return canName; } else { Role r = c.getField(field).getAnnotation(Role.class); if (r != null) { return r.value(); } return Role.VARIABLE; } } catch (NoSuchFieldException ex) { throw new ComponentException("No such field: " + field); } catch (SecurityException ex) { throw new ComponentException("Cannot access : " + field); } } } throw new ComponentException( "Cannot find component '" + object + "'. in '" + object + "." + field + "'"); }
/** Is c1 an inner class of c2? */ protected boolean isInnerClass(Class c1, final Class c2) { Class c = c1.getDeclaringClass(); if (c == null) { try { final Field f = c1.getField("declaring$Class$Reference$0"); c = (Class) f.get(null); } catch (final Exception e) { } } c1 = c; while (c != null) { if (c == c2) { return true; } c = c.getDeclaringClass(); if (c == null) { try { final Field f = c1.getField("declaring$Class$Reference$0"); c = (Class) f.get(null); } catch (final Exception e) { } } c1 = c; } return false; }
private void fillActivity() { ItemInfo item = mDbAdapter.getContentItem(mCategoryId, mIndex); Class res = R.drawable.class; int imageId = 0; try { imageId = res.getField(item.icon).getInt(null); } catch (Exception ex) { Log.w("ContentActivity", ex.getMessage()); } ImageView img = (ImageView) findViewById(R.id.list_view_item_icon); img.setImageResource(imageId); TextView text = (TextView) findViewById(R.id.list_view_item_text); text.setText(item.name); text = (TextView) findViewById(R.id.list_view_like_num); text.setText(Integer.toString(item.likeCount)); try { imageId = res.getField(item.picture).getInt(null); } catch (Exception ex) { Log.w("ContentActivity", ex.getMessage()); } img = (ImageView) findViewById(R.id.picture); img.setImageResource(imageId); text = (TextView) findViewById(R.id._text); text.setText(item.text); fillList(); }
private ImagePlus openImage(String directory, String name, String path) { Object o = tryOpen(directory, name, path); // if an image was returned, assume success if (o instanceof ImagePlus) return (ImagePlus) o; // try opening the file with LOCI Bio-Formats plugin - always check this last! // Do not call Bio-Formats if File>Import>Image Sequence is opening this file. if (o == null && (IJ.getVersion().compareTo("1.38j") < 0 || !IJ.redirectingErrorMessages()) && (new File(path).exists())) { Object loci = IJ.runPlugIn("loci.plugins.LociImporter", path); if (loci != null) { // plugin exists and was launched try { // check whether plugin was successful Class c = loci.getClass(); boolean success = c.getField("success").getBoolean(loci); boolean canceled = c.getField("canceled").getBoolean(loci); if (success || canceled) { width = IMAGE_OPENED; return null; } } catch (Exception exc) { } } } return null; } // openImage
public void updateControllerSettings(IFuelDock dock) { HashSet<ILandingPadAttachable> connectedTiles = dock.getConnectedTiles(); try { Class<?> controllerClass = Class.forName( "micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityLaunchController"); for (ILandingPadAttachable connectedTile : connectedTiles) { if (connectedTile != null) { TileEntity updatedTile = this.worldObj.getTileEntity(((TileEntity) connectedTile).getPos()); try { controllerClass.cast(updatedTile); } catch (ClassCastException e) { continue; } controllerClass.getField("attachedDock").set(updatedTile, dock); Boolean autoLaunchEnabled = controllerClass.getField("launchSchedulingEnabled").getBoolean(updatedTile); if (autoLaunchEnabled) { this.autoLaunchSetting = EnumAutoLaunch.values()[ controllerClass.getField("launchDropdownSelection").getInt(updatedTile)]; switch (this.autoLaunchSetting) { case INSTANT: // Small countdown to give player a moment to jump out of the rocket this.autoLaunchCountdown = 12; break; case TIME_10_SECONDS: this.autoLaunchCountdown = 200; break; case TIME_30_SECONDS: this.autoLaunchCountdown = 600; break; case TIME_1_MINUTE: this.autoLaunchCountdown = 1200; break; default: break; } } else { this.autoLaunchSetting = null; } break; } } } catch (Exception e) { e.printStackTrace(); } }
@Override protected void init() { try { Class clz = Class.forName("ic2.core.IC2"); clz.getField("ironName").get(null); clz.getField("displayNoUseItems").get(null); } catch (Exception e) { registerIC2Ores(); } }
@Test public void testBug377002() { try { final XExpression expression = this.expression("null"); final Procedure1<JvmEnumerationType> _function = new Procedure1<JvmEnumerationType>() { public void apply(final JvmEnumerationType it) { EList<JvmMember> _members = it.getMembers(); JvmEnumerationLiteral _enumerationLiteral = JvmModelGeneratorTest.this.builder.toEnumerationLiteral(expression, "WARN"); JvmModelGeneratorTest.this.builder.<JvmEnumerationLiteral>operator_add( _members, _enumerationLiteral); EList<JvmMember> _members_1 = it.getMembers(); JvmEnumerationLiteral _enumerationLiteral_1 = JvmModelGeneratorTest.this.builder.toEnumerationLiteral(expression, "ERROR"); JvmModelGeneratorTest.this.builder.<JvmEnumerationLiteral>operator_add( _members_1, _enumerationLiteral_1); EList<JvmMember> _members_2 = it.getMembers(); JvmEnumerationLiteral _enumerationLiteral_2 = JvmModelGeneratorTest.this.builder.toEnumerationLiteral(expression, "DEBUG"); JvmModelGeneratorTest.this.builder.<JvmEnumerationLiteral>operator_add( _members_2, _enumerationLiteral_2); EList<JvmMember> _members_3 = it.getMembers(); JvmTypeReference _typeForName = JvmModelGeneratorTest.this.references.getTypeForName( "java.lang.Object", expression); final Procedure1<JvmOperation> _function = new Procedure1<JvmOperation>() { public void apply(final JvmOperation it) { JvmModelGeneratorTest.this.builder.setBody(it, expression); } }; JvmOperation _method = JvmModelGeneratorTest.this.builder.toMethod( expression, "doStuff", _typeForName, _function); JvmModelGeneratorTest.this.builder.<JvmOperation>operator_add(_members_3, _method); } }; final JvmEnumerationType clazz = this.builder.toEnumerationType(expression, "my.test.Level", _function); Resource _eResource = expression.eResource(); final Class<? extends Object> compiled = this.compile(_eResource, clazz); Field _field = compiled.getField("WARN"); Assert.assertNotNull(_field); Field _field_1 = compiled.getField("ERROR"); Assert.assertNotNull(_field_1); Field _field_2 = compiled.getField("DEBUG"); Assert.assertNotNull(_field_2); Method _method = compiled.getMethod("doStuff"); Assert.assertNotNull(_method); } catch (Exception _e) { throw Exceptions.sneakyThrow(_e); } }
public static ItemStack getItemStack(String modid, String name, int stackSize, int metadata) { if (classNames.containsKey(modid)) { // Use classNames for (String classname : classNames.get(modid)) { try { Class klass = null; if (classname.split("\\$").length == 1) { klass = CrossModUtils.class.getClassLoader().loadClass(classname); } else { klass = CrossModUtils.class.getClassLoader().loadClass(classname.split("\\$")[0]); for (Class innerklass : klass.getDeclaredClasses()) { if (innerklass.getName().equals(classname)) klass = innerklass; } } if (klass != null) { Object o = klass.getField(name).get(null); if (o instanceof Block) return new ItemStack((Block) o, stackSize, metadata); else if (o instanceof Item) return new ItemStack((Item) o, stackSize, metadata); else if (o instanceof Integer) return new ItemStack(((Integer) o).intValue(), stackSize, metadata); else { try { int id = klass.getField(name).getInt(null); return new ItemStack(id, stackSize, metadata); } catch (Exception e) { AsieLibMod.log.warning( "Could not get right object for field " + name + " in class " + classNames.get(modid)); } } } } catch (Exception e) { e.printStackTrace(); } } // We're still here!? AsieLibMod.log.severe( "Could not load class for mod " + modid + ", trying worst-case alternatives - PROBABLY BROKEN"); } if (GameRegistry.findBlock(modid, name) != null) return new ItemStack(GameRegistry.findBlock(modid, name), stackSize, metadata); else if (GameRegistry.findItem(modid, name) != null) return new ItemStack(GameRegistry.findItem(modid, name), stackSize, metadata); else if (GameRegistry.findItemStack(modid, name, stackSize) != null) { ItemStack stack = GameRegistry.findItemStack(modid, name, stackSize); if (stack != null) stack.setItemDamage(metadata); return stack; } return null; // in case we already haven't }
/** * Return information about the scripting variables to be created. * * @param data the input data * @return VariableInfo array of variable information */ @SuppressWarnings("unchecked") public VariableInfo[] getVariableInfo(TagData data) { // loop through and expose all attributes List<VariableInfo> vars = new ArrayList<VariableInfo>(); try { String clazz = data.getAttributeString("className"); if (clazz == null) { clazz = Constants.class.getName(); } Class c = Class.forName(clazz); // if no var specified, get all if (data.getAttributeString("var") == null) { Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { String type = field.getType().getName(); vars.add( new VariableInfo( field.getName(), ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } else { String var = data.getAttributeString("var"); String type = c.getField(var).getType().getName(); vars.add( new VariableInfo( c.getField(var).getName(), ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } catch (Exception cnf) { log.error(cnf.getMessage()); cnf.printStackTrace(); } return vars.toArray(new VariableInfo[] {}); }
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Class<Foobar> cls = Foobar.class; System.out.println(cls.getField("i").get(null)); Foobar.i = 6; System.out.println(cls.getField("i").get(null)); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("foobar.out")); out.writeObject(cls); }
/** * Report product version information from common parsers. * * <p>Looks for version info in xerces.jar/xercesImpl.jar/crimson.jar. * * <p>//@todo actually look up version info in crimson manifest * * @param h Hashtable to put information in */ protected void checkParserVersion(Hashtable h) { if (null == h) h = new Hashtable(); try { final String XERCES1_VERSION_CLASS = "org.apache.xerces.framework.Version"; Class clazz = ObjectFactory.findProviderClass( XERCES1_VERSION_CLASS, ObjectFactory.findClassLoader(), true); // Found Xerces-J 1.x, grab it's version fields Field f = clazz.getField("fVersion"); String parserVersion = (String) f.get(null); h.put(VERSION + "xerces1", parserVersion); } catch (Exception e) { h.put(VERSION + "xerces1", CLASS_NOTPRESENT); } // Look for xerces1 and xerces2 parsers separately try { final String XERCES2_VERSION_CLASS = "org.apache.xerces.impl.Version"; Class clazz = ObjectFactory.findProviderClass( XERCES2_VERSION_CLASS, ObjectFactory.findClassLoader(), true); // Found Xerces-J 2.x, grab it's version fields Field f = clazz.getField("fVersion"); String parserVersion = (String) f.get(null); h.put(VERSION + "xerces2", parserVersion); } catch (Exception e) { h.put(VERSION + "xerces2", CLASS_NOTPRESENT); } try { final String CRIMSON_CLASS = "org.apache.crimson.parser.Parser2"; Class clazz = ObjectFactory.findProviderClass(CRIMSON_CLASS, ObjectFactory.findClassLoader(), true); // @todo determine specific crimson version h.put(VERSION + "crimson", CLASS_PRESENT); } catch (Exception e) { h.put(VERSION + "crimson", CLASS_NOTPRESENT); } }
@CallerSensitive public <T> Prop<T> type() { Prop on = this; if (!isCannon()) { Prop<T> already = (Prop<T>) findCannon(); if (already == null) { toCannon(); on.setCannon(); } else { on = already; } } Class c = sun.reflect.Reflection.getCallerClass(2); on.definedInClass = c; Field f = null; try { f = c.getField(name); } catch (NoSuchFieldException e) { try { f = c.getField("_" + name); } catch (NoSuchFieldException e3) { if (name.startsWith("_")) try { f = c.getField(name.substring(1)); } catch (NoSuchFieldException e1) { if (name.startsWith("__")) try { f = c.getField(name.substring(1)); } catch (NoSuchFieldException e2) { } } } } if (f == null) throw new IllegalStateException( " cannot type a Dict.Prop<T> that we can't find. Name is :" + name + " class is :" + c); on.typeInformation = Conversions.linearize(f.getGenericType()); on.typeInformation.remove(0); return (Prop<T>) on; }
/** * Prints one Unicode property value per line, along with its aliases, if any, for the given * unicodeVersion. * * @param unicodeVersion The Unicode version to print property values and aliases for * @throws UnicodeProperties.UnsupportedUnicodeVersionException if unicodeVersion is not supported */ private static void printUnicodePropertyValuesAndAliases(String unicodeVersion) throws UnicodeProperties.UnsupportedUnicodeVersionException { Pattern versionPattern = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.\\d+)?"); Matcher matcher = versionPattern.matcher(unicodeVersion); if (!matcher.matches()) { throw new UnicodeProperties.UnsupportedUnicodeVersionException(); } String underscoreVersion = matcher.group(1) + (null == matcher.group(2) ? "_0" : "_" + matcher.group(2)); String[] propertyValues; String[] propertyValueAliases; try { Class<?> clazz = Class.forName("jflex.unicode.data.Unicode_" + underscoreVersion); Field field = clazz.getField("propertyValues"); propertyValues = (String[]) field.get(null); field = clazz.getField("propertyValueAliases"); propertyValueAliases = (String[]) field.get(null); } catch (Exception e) { throw new UnicodeProperties.UnsupportedUnicodeVersionException(); } SortedMap<String, SortedSet<String>> propertyValuesToAliases = new TreeMap<String, SortedSet<String>>(); for (String value : propertyValues) { propertyValuesToAliases.put(value, new TreeSet<String>()); } for (int i = 0; i < propertyValueAliases.length; i += 2) { String alias = propertyValueAliases[i]; String value = propertyValueAliases[i + 1]; SortedSet<String> aliases = propertyValuesToAliases.get(value); if (null == aliases) { aliases = new TreeSet<String>(); propertyValuesToAliases.put(value, aliases); } aliases.add(alias); } for (Map.Entry<String, SortedSet<String>> entry : propertyValuesToAliases.entrySet()) { String value = entry.getKey(); SortedSet<String> aliases = entry.getValue(); Out.print(value); if (aliases.size() > 0) { for (String alias : aliases) { Out.print(", " + alias); } } Out.println(""); } }
protected void checkClass(Class<?> c) throws Exception { Object o = c.newInstance(); Method m = c.getMethod("m"); m.invoke(o); Field f = c.getField("timer"); assertTrue(f.getLong(null) > 0); }
/** * 获取状态栏高度 * * @param activity * @return */ public int getStatusHeight(Activity activity) { int statusHeight = 0; Rect localRect = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); statusHeight = localRect.top; if (0 == statusHeight) { Class<?> localClass; try { localClass = Class.forName("com.android.internal.R$dimen"); Object localObject = localClass.newInstance(); int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString()); statusHeight = activity.getResources().getDimensionPixelSize(i5); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } return statusHeight; }
/** * Returns the label or message of the specified key. * * <ul> * <li>If key is "mesg:class:MMM", Messages.get(class.MMM) is called * <li>Otherwise, {@link Labels#getLabel(String)} is called. * </ul> * * @see #getLabel(String, Object[]) */ public static final String getLabel(String key) { if (key == null) return ""; if (key.startsWith("mesg:")) { final int j = key.lastIndexOf(':'); if (j > 5) { final String clsnm = key.substring(5, j); final String fldnm = key.substring(j + 1); try { final Class cls = Classes.forNameByThread(clsnm); final Field fld = cls.getField(fldnm); return Messages.get(((Integer) fld.get(null)).intValue()); } catch (ClassNotFoundException ex) { log.warn("Class not found: " + clsnm, ex); } catch (NoSuchFieldException ex) { log.warn("Field not found: " + fldnm, ex); } catch (IllegalAccessException ex) { log.warn("Field not accessible: " + fldnm, ex); } } else if (log.isDebugEnabled()) { log.debug("Not a valid format: " + key); } } return Labels.getLabel(key); }
public void testChainedConstructor() throws Exception { Class cls = loadAndPatchClass("TestChainedConstructor.form", "ChainedConstructorTest"); Field scrollPaneField = cls.getField("myScrollPane"); Object instance = cls.newInstance(); JScrollPane scrollPane = (JScrollPane) scrollPaneField.get(instance); assertNotNull(scrollPane.getViewport().getView()); }
public void fetchAdForUrl(String url) { mCurrentTaskId++; Log.i("MoPub", "Fetching ad for task #" + mCurrentTaskId); if (mCurrentTask != null) { mCurrentTask.cancel(true); } mCurrentTask = new AdFetchTask(this); if (Build.VERSION.SDK_INT >= VERSION_CODE_ICE_CREAM_SANDWICH) { Class<?> cls = AdFetchTask.class; Class<?>[] parameterTypes = {Executor.class, Object[].class}; String[] parameters = {url}; try { Method method = cls.getMethod("executeOnExecutor", parameterTypes); Field field = cls.getField("THREAD_POOL_EXECUTOR"); method.invoke(mCurrentTask, field.get(cls), parameters); } catch (NoSuchMethodException exception) { Log.d("MoPub", "Error executing AdFetchTask on ICS+, method not found."); } catch (InvocationTargetException exception) { Log.d("MoPub", "Error executing AdFetchTask on ICS+, thrown by executeOnExecutor."); } catch (Exception exception) { Log.d("MoPub", "Error executing AdFetchTask on ICS+: " + exception.toString()); } } else { mCurrentTask.execute(url); } }
@Test public void testStaticField() { Class<?> c = ClassWithFields.class; try { StaticField sf = new StaticField(c.getField("fourField")); FieldGetter rhs = new FieldGetter(sf); // types assertTrue("Should be no input types", rhs.getInputTypes().isEmpty()); assertEquals("Output type should match type of field", sf.getType(), rhs.getOutputType()); // code generation String expected = "int i0 = randoop.operation.ClassWithFields.fourField;" + Globals.lineSep; Statement st = new Statement(rhs); Sequence seq = new Sequence().extend(rhs, new ArrayList<Variable>()); Variable var = new Variable(seq, 0); StringBuilder b = new StringBuilder(); st.appendCode(var, new ArrayList<Variable>(), b); assertEquals("Expect initialization of variable from static field", expected, b.toString()); // execution - should be 4 (haven't changed value yet) NormalExecution expectedExec = new NormalExecution(4, 0); NormalExecution actualExec = (NormalExecution) rhs.execute(new Object[0], null); assertTrue( "Execution should simply return value", expectedExec.getRuntimeValue().equals(actualExec.getRuntimeValue()) && expectedExec.getExecutionTime() == actualExec.getExecutionTime()); } catch (NoSuchFieldException e) { fail("test failed because field in test class not found"); } catch (SecurityException e) { fail("test failed because of unexpected security exception"); } }
public void afterPropertiesSet() throws MBeanServerNotFoundException { try { String jndiName = this.mbeanHomeName; if (jndiName == null) { /* * jndiName = MBeanHome.LOCAL_JNDI_NAME; */ Class mbeanHomeClass = ClassUtils.forName(WEBLOGIC_MBEAN_HOME_CLASS); jndiName = (String) mbeanHomeClass.getField(LOCAL_JNDI_NAME_FIELD).get(null); } Object mbeanHome = lookup(jndiName); /* * this.mbeanServer = mbeanHome.getMBeanServer(); */ this.mbeanServer = (MBeanServer) mbeanHome.getClass().getMethod(GET_MBEAN_SERVER_METHOD, null).invoke(mbeanHome, null); } catch (NamingException ex) { throw new MBeanServerNotFoundException( "Could not find WebLogic's MBeanHome object in JNDI", ex); } catch (ClassNotFoundException ex) { throw new MBeanServerNotFoundException("Could not find WebLogic's MBeanHome class", ex); } catch (InvocationTargetException ex) { throw new MBeanServerNotFoundException( "WebLogic's MBeanHome.getMBeanServer method failed", ex.getTargetException()); } catch (Exception ex) { throw new MBeanServerNotFoundException( "Could not access WebLogic's MBeanHome/getMBeanServer method", ex); } }
private String getValue(QualifiedName name, ASTNode astNode, final JstType jstType) { TranslateInfo tInfo = TranslateCtx.ctx().getTranslateInfo(jstType); String typeName = name.getQualifier().getFullyQualifiedName(); String fullName = tInfo.getImported(typeName); try { Class<?> toClass = Class.forName(fullName); Field field = toClass.getField(name.getName().toString()); return (String) field.get(toClass); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
public static Font getFont( String name, int size, int style, boolean strikeout, boolean underline) { if (name.equals("Arial") && SWTResourceManager.isMac()) { size += 2; } String fontName = name + "|" + size + "|" + style + "|" + strikeout + "|" + underline; if (resources.containsKey(fontName)) return (Font) resources.get(fontName); FontData fd = new FontData(name, size, style); if (strikeout || underline) { try { Class<?> lfCls = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); Object lf = FontData.class.getField("data").get(fd); if (lf != null && lfCls != null) { if (strikeout) lfCls.getField("lfStrikeOut").set(lf, new Byte((byte) 1)); if (underline) lfCls.getField("lfUnderline").set(lf, new Byte((byte) 1)); } } catch (Throwable e) { System.err.println( "Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); } } Font font = new Font(Display.getDefault(), fd); resources.put(fontName, font); return font; }
protected String getClpServletContextName( Class<?> clpMessageListenerClass, MessageListener clpMessageListener) throws Exception { Exception e = null; try { Method servletContextNameMethod = clpMessageListenerClass.getMethod("getServletContextName"); String clpServletContextName = (String) servletContextNameMethod.invoke(null); return clpServletContextName; } catch (Exception e1) { e = e1; } try { Field servletContextNameField = clpMessageListenerClass.getField("SERVLET_CONTEXT_NAME"); Object clpServletContextName = servletContextNameField.get(clpMessageListener); return clpServletContextName.toString(); } catch (Exception e2) { } throw e; }
/** * 判断Class是否是基本包装类型 * * @param clz * @return */ public static boolean isWrapClass(Class<?> clz) { try { return ((Class<?>) clz.getField("TYPE").get(null)).isPrimitive(); } catch (Exception e) { return false; } }
/** * Register a class with the factory from its class name. We override the standard implementation * to get the mime type from the class and use that as the key to register the class with the * factory. * * @param className The class name which will be regiestered. * @return boolean true if the class was registered otherwise false. */ protected boolean registerAssoc(String className) { boolean registeredSomething = false; // LOG.debug( "Registering : " + className ); try { Class docClass = Class.forName(className); Instantiator instantiator = (Instantiator) (docClass.getField("INSTANTIATOR").get(null)); MimeMediaType[] mimeTypes = instantiator.getSupportedMimeTypes(); for (int eachType = 0; eachType < mimeTypes.length; eachType++) { // LOG.debug( " Registering Type : " + mimeTypes[eachType].getMimeMediaType() ); registeredSomething |= registerInstantiator(mimeTypes[eachType], instantiator); } } catch (Exception all) { if (LOG.isEnabledFor(Level.WARN)) { LOG.warn("Failed to register '" + className + "'", all); } } return registeredSomething; }
public boolean isAvailable() { try { // Diagnostic was introduced in the Java 1.6 compiler Class<?> diagnostic = Class.forName("javax.tools.Diagnostic"); diagnostic.getMethod("getKind"); // javax.lang.model.SourceVersion.RELEASE_7 field introduced in Java 7 Class<?> sourceVersion = Class.forName("javax.lang.model.SourceVersion"); sourceVersion.getField("RELEASE_7"); // only exists in Java 7 and later releases // javax.tools.Diagnostic and javax.lang.model.SourceVersion are also found in rt.jar; // to test if tools.jar is available, we need to test for a class only found in tools.jar Class.forName("com.sun.tools.javac.main.JavaCompiler"); // This is the class that javax.tools.ToolProvider.getSystemJavaCompiler() uses // We create an instance of that class directly, bypassing ToolProvider, because ToolProvider // returns null // if DrJava is started with just the JRE, instead of with the JDK, even if tools.jar is later // made available // to the class loader. JavaCompiler compiler = (JavaCompiler) (Class.forName("com.sun.tools.javac.api.JavacTool").newInstance()); return (compiler != null); } catch (Exception e) { return false; } catch (LinkageError e) { return false; } }
public static int getResourseIdByName(String packageName, String className, String name) { Class r = null; int id = 0; try { r = Class.forName(packageName + ".R"); Class[] classes = r.getClasses(); Class desireClass = null; for (int i = 0; i < classes.length; i++) { if (classes[i].getName().split("\\$")[1].equals(className)) { desireClass = classes[i]; break; } } if (desireClass != null) id = desireClass.getField(name).getInt(desireClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return id; }
/** * @param clazz * @param constantName * @param declared * @return */ public static String getStringConstant(Class<?> clazz, String constantName, boolean declared) { Field compType = null; try { // check if there's a // public static final String COMPONENT_TYPE = "..."; compType = declared ? clazz.getDeclaredField(constantName) : clazz.getField(constantName); } catch (SecurityException e) { // if no such field, fall through } catch (NoSuchFieldException e) { // if no such field, fall through } if (null == compType) return null; int modifiers = compType.getModifiers(); if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers) || !Modifier.isFinal(modifiers) || String.class != compType.getType()) { return null; } try { return (String) compType.get(null); } catch (IllegalArgumentException e1) { // shouldn't happen - the arg is of the correct type e1.printStackTrace(); } catch (IllegalAccessException e1) { // shouldn't happen - the method is public e1.printStackTrace(); } catch (NullPointerException e1) { // shouldn't happen - allowed a null arg when // the field is static e1.printStackTrace(); } return null; }