Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

In this page you can find the example usage for java.lang Class getField.

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:net.kseek.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();//from  ww w.  j  ava 2  s. com
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.kseek.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static void showAlertNotification(String aImageUrl, String aAlertTitle, String aAlertText,
        String aAlertCookie, String aAlertName) {
    Log.i(LOGTAG,/* ww w .  jav  a 2  s .  co  m*/
            "GeckoAppShell.showAlertNotification\n" + "- image = '" + aImageUrl + "'\n" + "- title = '"
                    + aAlertTitle + "'\n" + "- text = '" + aAlertText + "'\n" + "- cookie = '" + aAlertCookie
                    + "'\n" + "- name = '" + aAlertName + "'");

    int icon = R.drawable.icon; // Just use the app icon by default

    Uri imageUri = Uri.parse(aImageUrl);
    String scheme = imageUri.getScheme();
    if ("drawable".equals(scheme)) {
        String resource = imageUri.getSchemeSpecificPart();
        resource = resource.substring(resource.lastIndexOf('/') + 1);
        try {
            Class<R.drawable> drawableClass = R.drawable.class;
            Field f = drawableClass.getField(resource);
            icon = f.getInt(null);
        } catch (Exception e) {
        } // just means the resource doesn't exist
        imageUri = null;
    }

    int notificationID = aAlertName.hashCode();

    // Remove the old notification with the same ID, if any
    removeNotification(notificationID);

    AlertNotification notification = new AlertNotification(GeckoApp.mAppContext, notificationID, icon,
            aAlertTitle, aAlertText, System.currentTimeMillis());

    // The intent to launch when the user clicks the expanded notification
    Intent notificationIntent = new Intent(GeckoApp.ACTION_ALERT_CLICK);
    notificationIntent.setClassName(GeckoApp.mAppContext,
            GeckoApp.mAppContext.getPackageName() + ".NotificationHandler");

    // Put the strings into the intent as an URI "alert:<name>#<cookie>"
    Uri dataUri = Uri.fromParts("alert", aAlertName, aAlertCookie);
    notificationIntent.setData(dataUri);

    PendingIntent contentIntent = PendingIntent.getBroadcast(GeckoApp.mAppContext, 0, notificationIntent, 0);
    notification.setLatestEventInfo(GeckoApp.mAppContext, aAlertTitle, aAlertText, contentIntent);
    notification.setCustomIcon(imageUri);
    // The intent to execute when the status entry is deleted by the user with the "Clear All Notifications" button
    Intent clearNotificationIntent = new Intent(GeckoApp.ACTION_ALERT_CLEAR);
    clearNotificationIntent.setClassName(GeckoApp.mAppContext,
            GeckoApp.mAppContext.getPackageName() + ".NotificationHandler");
    clearNotificationIntent.setData(dataUri);
    notification.deleteIntent = PendingIntent.getBroadcast(GeckoApp.mAppContext, 0, clearNotificationIntent, 0);

    mAlertNotifications.put(notificationID, notification);

    notification.show();

    Log.i(LOGTAG, "Created notification ID " + notificationID);
}

From source file:net.minecraftforge.fml.client.FMLClientHandler.java

private void detectOptifine() {
    try {//from   ww w . j  ava 2  s . c  o  m
        Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader());
        String optifineVersion = (String) optifineConfig.getField("VERSION").get(null);
        Map<String, Object> dummyOptifineMeta = ImmutableMap.<String, Object>builder().put("name", "Optifine")
                .put("version", optifineVersion).build();
        InputStream optifineModInfoInputStream = getClass().getResourceAsStream("optifinemod.info");
        try {
            ModMetadata optifineMetadata = MetadataCollection.from(optifineModInfoInputStream, "optifine")
                    .getMetadataForId("optifine", dummyOptifineMeta);
            optifineContainer = new DummyModContainer(optifineMetadata);
            FMLLog.info("Forge Mod Loader has detected optifine %s, enabling compatibility features",
                    optifineContainer.getVersion());
        } finally {
            IOUtils.closeQuietly(optifineModInfoInputStream);
        }
    } catch (Exception e) {
        optifineContainer = null;
    }
}

From source file:com.fluidops.iwb.api.ProviderServiceImpl.java

@Override
public Object invoke(String serviceName, String method, Object[] params) throws Exception {
    sessionProvider = null;//from ww  w  .j a  v a2 s .  com
    Class providerClass = null;

    for (String tempProviderClass : EndpointImpl.api().getProviderService().getProviderClasses()) {
        Class c = DynamicScriptingSupport.loadClass(tempProviderClass);
        if (c.getSimpleName().equals(method)) {
            providerClass = c;
            break;
        }
    }

    // TODO Is the "method" arg the constructor? Can it be any other method in the provider??!?
    if (providerClass == null)
        throw new Exception("Provider " + method + " not found or not enabled.");

    AbstractFlexProvider p = (AbstractFlexProvider) providerClass.newInstance();
    Class config = p.getConfigClass();
    Serializable object = (Serializable) config.newInstance();

    for (MethodMetaData mmd : getMetaData().methods)
        if (mmd.name.equals(method)) {
            int index = 0;
            for (ParamMetaData mp : mmd.params) {
                Field f = config.getField(mp.param.getName());
                f.set(object, params[index++]);
            }
        }

    List<Statement> res = new ArrayList<Statement>();
    p.config = object;
    p.gather(res);

    logger.info("Result size = " + res.size());
    Repository rep = new SailRepository(new MemoryStore());
    rep.initialize();

    RepositoryConnection con = rep.getConnection();
    try {
        con.add(res);
        FileOutputStream fos = new FileOutputStream(p.getClass().getSimpleName() + ".nt");
        NTriplesWriter ntwriter = new NTriplesWriter(fos);
        con.exportStatements(null, null, null, false, ntwriter);

        ntwriter = null;
        fos.flush();
        fos.close();

        sessionProvider = p;

        if (res.isEmpty())
            return "0 results";
        else
            return res.size() + " results: " + res.get(0) + " ...";

    } finally {
        con.close();
    }
}

From source file:org.modeldriven.fuml.assembly.ElementAssembler.java

@SuppressWarnings("unchecked")
private void assembleSingularPrimitiveFeature(Property property, Object value, Class javaType)
        throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException,
        InstantiationException, NoSuchFieldException {
    String methodName = "set" + property.getName().substring(0, 1).toUpperCase()
            + property.getName().substring(1);
    Object[] args = { value };/*from  w  w  w. j  a v  a2  s .  c om*/
    try {
        Method setter = this.getTargetClass().getMethod(methodName, new Class[] { javaType });
        setter.invoke(this.getTargetObject(), args);
    } catch (NoSuchMethodException e) {
        try {
            Object targetObject = this.getTargetObject();
            Class targetClass = targetObject.getClass();
            Field field = targetClass.getField(property.getName());
            field.set(targetObject, value);
        } catch (NoSuchFieldException e2) {
            String msg = "no fUML (" + this.getTargetObject().getClass().getName() + ") setter method named '"
                    + methodName + "' or public field found for primitive feature " + "<" + javaType.getName()
                    + "> " + this.getPrototype().getName() + "." + property.getName();
            log.warn(msg);
        }
    }
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

private void initActionBar() {
    Class<?> windowClass = Window.class;
    try {//from  ww w  . j  a v a2 s.c o  m
        Field field = windowClass.getField("FEATURE_ACTION_BAR");
        int fieldValue = field.getInt(null);
        this.getWindow().requestFeature(fieldValue);
    } catch (NoSuchFieldException e) {
        // DOES NOTHING
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:alpha.portal.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified
 * scope./*from ww  w.  java 2s .  c o m*/
 * 
 * @return int
 * @throws JspException
 *             if processing fails
 */
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (this.scope != null) {
        toScope = this.getScope(this.scope);
    }

    try {
        c = Class.forName(this.clazz);
    } catch (final ClassNotFoundException cnf) {
        this.log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (this.var == null) {
            final Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (final Field field : fields) {
                this.pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                final Object value = c.getField(this.var).get(this);
                this.pageContext.setAttribute(c.getField(this.var).getName(), value, toScope);
            } catch (final NoSuchFieldException nsf) {
                this.log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (final IllegalAccessException iae) {
        this.log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (Tag.SKIP_BODY);
}

From source file:org.red5.io.amf.Input.java

/**
 * Reads the input as a bean and returns an object
*
 * @param deserializer       Deserializer used
 * @param bean               Input as bean
 * @return                   Decoded object
 *///from w w  w.j  a v  a2s  .  c  o m
@SuppressWarnings("unchecked")
protected Object readBean(Deserializer deserializer, Object bean) {
    log.debug("read bean");
    storeReference(bean);
    Class theClass = bean.getClass();
    while (hasMoreProperties()) {
        String name = readPropertyName();
        Class t = getPropertyType(bean, name);
        log.debug("property: {}", name);
        Object property = deserializer.deserialize(this, t);
        log.debug("val: {}", property);
        //log.debug("val: "+property.getClass().getName());
        try {
            if (property != null) {
                try {
                    final Field field = theClass.getField(name);
                    if (!t.isAssignableFrom(property.getClass())) {
                        property = ConversionUtils.convert(property, t);
                    }
                    field.set(bean, property);
                } catch (Exception ex2) {
                    BeanUtils.setProperty(bean, name, property);
                }
            } else {
                log.debug("Skipping null property: {}", name);
            }
        } catch (Exception ex) {
            log.error("Error mapping property: {} ({})", name, property);
        }
        if (hasMoreProperties()) {
            skipPropertySeparator();
        }
    }
    skipEndObject();
    return bean;
}

From source file:org.apache.axis2.transport.testkit.tests.TestResourceSet.java

TestResource[] findResources(Class<?> clazz, boolean allowAutoCreate) {
    List<TestResource> result = new LinkedList<TestResource>();
    if (parent != null) {
        result.addAll(Arrays.asList(parent.findResources(clazz, false)));
    }//from ww  w . jav  a  2  s . c  o m
    for (TestResource resource : resolvedResources) {
        if (clazz.isInstance(resource.getInstance())) {
            result.add(resource);
        }
    }
    List<TestResource> unresolvedMatchingResources = new LinkedList<TestResource>();
    for (TestResource resource : unresolvedResources) {
        if (clazz.isInstance(resource.getInstance())) {
            unresolvedMatchingResources.add(resource);
        }
    }
    for (TestResource resource : unresolvedMatchingResources) {
        resolveResource(resource);
        result.add(resource);
    }
    if (allowAutoCreate && result.isEmpty()) {
        TestResource resource;
        try {
            Field field = clazz.getField("INSTANCE");
            resource = new TestResource(field.get(null));
        } catch (Throwable ex) {
            resource = null;
        }
        if (resource != null) {
            unresolvedResources.add(resource);
            resolveResource(resource);
            result.add(resource);
        }
    }
    return result.toArray(new TestResource[result.size()]);
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.secured.TBSONSecuredWrapper.java

public void secureThriftFields(Class<? extends TBase> tbase, boolean hash, TFieldIdEnum... fields)
        throws Exception {
    Map<Short, ThriftSecuredField> classSecuredFields = securedFields.get(tbase);
    if (classSecuredFields == null) {
        classSecuredFields = new ConcurrentHashMap<>();
    }/*from w ww . java  2 s. co m*/

    // get the Field class
    Class<?> fieldClass = null;
    Class<?>[] innerClasses = tbase.getClasses();
    for (Class<?> innerClass : innerClasses) {
        if ("_Fields".equals(innerClass.getSimpleName())) {
            fieldClass = innerClass;
            break;
        }
    }

    // extract _Fields
    Class[] findByNameArgs = new Class[1];
    findByNameArgs[0] = String.class;
    Method findByNameMethod = fieldClass.getMethod("findByName", findByNameArgs);

    // extract metadataMap
    Field metafaField = tbase.getField("metaDataMap");
    Map<?, FieldMetaData> metaDataMap = (Map<?, org.apache.thrift.meta_data.FieldMetaData>) metafaField
            .get(tbase);

    for (TFieldIdEnum field : fields) {
        // get the _Field instance
        org.apache.thrift.TFieldIdEnum tfieldEnum = (TFieldIdEnum) findByNameMethod.invoke(null,
                field.getFieldName());

        // get the matadata
        FieldMetaData fieldMetaData = metaDataMap.get(tfieldEnum);

        // only string are supported
        switch (fieldMetaData.valueMetaData.type) {
        case TType.STRING:
            break;

        case TType.MAP:
            MapMetaData mapMetaData = (MapMetaData) fieldMetaData.valueMetaData;

            if (mapMetaData.valueMetaData.type != TType.STRING) {
                throw new UnsupportedTTypeException("Unsupported secured type - FIELD:" + field.getFieldName()
                        + " TYPE:" + mapMetaData.valueMetaData.type);
            }
            break;
        default:
            throw new UnsupportedTTypeException("Unsupported secured type - FIELD:" + field.getFieldName()
                    + " TYPE:" + fieldMetaData.valueMetaData.type);
        }

        classSecuredFields.put(field.getThriftFieldId(), new ThriftSecuredField(true, hash));
    }

    securedFields.put(tbase, classSecuredFields);
}