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:fr.inria.atlanmod.neoemf.graph.blueprints.datastore.BlueprintsPersistenceBackendFactory.java

@Override
public BlueprintsPersistenceBackend createPersistentBackend(File file, Map<?, ?> options)
        throws InvalidDataStoreException {
    BlueprintsPersistenceBackend graphDB = null;
    PropertiesConfiguration neoConfig = null;
    PropertiesConfiguration configuration = null;
    try {/*from   w  ww .  j  a  v  a2  s . c o  m*/
        // Try to load previous configurations
        Path path = Paths.get(file.getAbsolutePath()).resolve(CONFIG_FILE);
        try {
            configuration = new PropertiesConfiguration(path.toFile());
        } catch (ConfigurationException e) {
            throw new InvalidDataStoreException(e);
        }
        // Initialize value if the config file has just been created
        if (!configuration.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) {
            configuration.setProperty(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE,
                    BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE_DEFAULT);
        } else if (options.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) {
            // The file already existed, check that the issued options
            // are not conflictive
            String savedGraphType = configuration
                    .getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE);
            String issuedGraphType = options.get(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)
                    .toString();
            if (!savedGraphType.equals(issuedGraphType)) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, "Unable to create graph as type " + issuedGraphType
                        + ", expected graph type was " + savedGraphType + ")");
                throw new InvalidDataStoreException("Unable to create graph as type " + issuedGraphType
                        + ", expected graph type was " + savedGraphType + ")");
            }
        }

        // Copy the options to the configuration
        for (Entry<?, ?> e : options.entrySet()) {
            configuration.setProperty(e.getKey().toString(), e.getValue().toString());
        }

        // Check we have a valid graph type, it is needed to get the
        // graph name
        String graphType = configuration.getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE);
        if (graphType == null) {
            throw new InvalidDataStoreException("Graph type is undefined for " + file.getAbsolutePath());
        }

        String[] segments = graphType.split("\\.");
        if (segments.length >= 2) {
            String graphName = segments[segments.length - 2];
            String upperCaseGraphName = Character.toUpperCase(graphName.charAt(0)) + graphName.substring(1);
            String configClassQualifiedName = MessageFormat.format(
                    "fr.inria.atlanmod.neoemf.graph.blueprints.{0}.config.Blueprints{1}Config", graphName,
                    upperCaseGraphName);
            try {
                ClassLoader classLoader = BlueprintsPersistenceBackendFactory.class.getClassLoader();
                Class<?> configClass = classLoader.loadClass(configClassQualifiedName);
                Field configClassInstanceField = configClass.getField("eINSTANCE");
                AbstractBlueprintsConfig configClassInstance = (AbstractBlueprintsConfig) configClassInstanceField
                        .get(configClass);
                Method configMethod = configClass.getMethod("putDefaultConfiguration", Configuration.class,
                        File.class);
                configMethod.invoke(configClassInstance, configuration, file);
                Method setGlobalSettingsMethod = configClass.getMethod("setGlobalSettings");
                setGlobalSettingsMethod.invoke(configClassInstance);
            } catch (ClassNotFoundException e1) {
                NeoLogger.log(NeoLogger.SEVERITY_WARNING,
                        "Unable to find the configuration class " + configClassQualifiedName);
                e1.printStackTrace();
            } catch (NoSuchFieldException e2) {
                NeoLogger.log(NeoLogger.SEVERITY_WARNING,
                        MessageFormat.format(
                                "Unable to find the static field eINSTANCE in class Blueprints{0}Config",
                                upperCaseGraphName));
                e2.printStackTrace();
            } catch (NoSuchMethodException e3) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR,
                        MessageFormat.format(
                                "Unable to find configuration methods in class Blueprints{0}Config",
                                upperCaseGraphName));
                e3.printStackTrace();
            } catch (InvocationTargetException e4) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format(
                        "An error occured during the exection of a configuration method", upperCaseGraphName));
                e4.printStackTrace();
            } catch (IllegalAccessException e5) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format(
                        "An error occured during the exection of a configuration method", upperCaseGraphName));
                e5.printStackTrace();
            }
        } else {
            NeoLogger.log(NeoLogger.SEVERITY_WARNING, "Unable to compute graph type name from " + graphType);
        }

        Graph baseGraph = null;
        try {
            baseGraph = GraphFactory.open(configuration);
        } catch (RuntimeException e) {
            throw new InvalidDataStoreException(e);
        }
        if (baseGraph instanceof KeyIndexableGraph) {
            graphDB = new BlueprintsPersistenceBackend((KeyIndexableGraph) baseGraph);
        } else {
            NeoLogger.log(NeoLogger.SEVERITY_ERROR,
                    "Graph type " + file.getAbsolutePath() + " does not support Key Indices");
            throw new InvalidDataStoreException(
                    "Graph type " + file.getAbsolutePath() + " does not support Key Indices");
        }
        // Save the neoconfig file
        Path neoConfigPath = Paths.get(file.getAbsolutePath()).resolve(NEO_CONFIG_FILE);
        try {
            neoConfig = new PropertiesConfiguration(neoConfigPath.toFile());
        } catch (ConfigurationException e) {
            throw new InvalidDataStoreException(e);
        }
        if (!neoConfig.containsKey(BACKEND_PROPERTY)) {
            neoConfig.setProperty(BACKEND_PROPERTY, BLUEPRINTS_BACKEND);
        }
    } finally {
        if (configuration != null) {
            try {
                configuration.save();
            } catch (ConfigurationException e) {
                // Unable to save configuration, supposedly it's a minor error,
                // so we log it without rising an exception
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, e);
            }
        }
        if (neoConfig != null) {
            try {
                neoConfig.save();
            } catch (ConfigurationException e) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, e);
            }
        }
    }
    return graphDB;
}

From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java

private void loadFallacies() {
    InputStream jsonStream = this.getResources().openRawResource(R.raw.fallacies);
    JSONObject jsonObject;//from  w  w w  . j a  v a 2s  .  c o m
    JSONArray jsonFallacies;
    JSONObject jsonFallacy;
    Fallacy eachFallacy;

    try {

        jsonObject = new JSONObject(convertStreamToString(jsonStream));
        jsonFallacies = jsonObject.getJSONArray("fallacies");
        fallacies = new ArrayList<Fallacy>();
        mFallacies = new LinkedHashMap<String, Fallacy>();
        for (int i = 0, m = jsonFallacies.length(); i < m; i++) {
            jsonFallacy = jsonFallacies.getJSONObject(i);
            eachFallacy = new Fallacy();
            eachFallacy.setName(jsonFallacy.getString("name"));
            eachFallacy.setTitle(jsonFallacy.getString("title"));
            eachFallacy.setDescription(jsonFallacy.getString("description"));
            eachFallacy.setExample(jsonFallacy.getString("example"));
            eachFallacy.setSortOrder(jsonFallacy.getString("sortorder"));
            eachFallacy.setColor(jsonFallacy.getInt("color"));

            String iconName = jsonFallacy.getString("icon");

            try {
                Class<?> drawableClass = R.drawable.class; // replace package
                Field drawableField = drawableClass.getField(iconName);
                int drawableId = (Integer) drawableField.get(null);
                Drawable drawable = this.getResources().getDrawable(drawableId);
                eachFallacy.setIcon(drawable);
            } catch (Exception e) {
                // NoSuchFieldException, IllegalAccessException, IllegalArgumentException, NotFoundException
                // On most any exception, use placeholder
                Drawable backup = this.getResources().getDrawable(R.drawable.empty);
                eachFallacy.setIcon(backup);
            }

            //TODO One or the other
            fallacies.add(eachFallacy);
            mFallacies.put(eachFallacy.getName(), eachFallacy);
        }

    } catch (JSONException e1) {
        e1.printStackTrace();
    }

}

From source file:egovframework.rte.itl.webservice.service.impl.MessageConverterImpl.java

@SuppressWarnings("unchecked")
public Object convertToValueObject(Object source, Type type)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
    LOG.debug("convertToValueObject(source = " + source + ", type = " + type + ")");

    if (type instanceof PrimitiveType) {
        LOG.debug("Type is a Primitive Type");
        return source;
    } else if (type instanceof ListType) {
        LOG.debug("Type is a List Type");

        ListType listType = (ListType) type;
        Object[] components = ((Collection<?>) source).toArray();

        Class<?> arrayClass = classLoader.loadClass(listType);
        Object array = Array.newInstance(arrayClass.getComponentType(), components.length);

        for (int i = 0; i < components.length; i++) {
            Array.set(array, i, convertToValueObject(components[i], listType.getElementType()));
        }/*from  w  w w  .j a va 2 s. com*/
        return array;
    } else if (type instanceof RecordType) {
        LOG.debug("Type is a Record(Map) Type");

        RecordType recordType = (RecordType) type;
        Map<String, Object> map = (Map<String, Object>) source;

        Class<?> recordClass = classLoader.loadClass(recordType);
        Object record = recordClass.newInstance();

        for (Entry<String, Object> entry : map.entrySet()) {
            Object fieldValue = convertToValueObject(entry.getValue(), recordType.getFieldType(entry.getKey()));
            recordClass.getField(entry.getKey()).set(record, fieldValue);
        }
        return record;
    }
    LOG.error("Type is invalid");
    throw new InstantiationException();
}

From source file:org.hibernate.ejb.metamodel.AbstractAttribute.java

/**
 * Used by JDK serialization...//from   w  ww . j a  va 2 s.  c o  m
 * 
 * @param ois
 *            The input stream from which we are being read...
 * @throws java.io.IOException
 *             Indicates a general IO stream exception
 * @throws ClassNotFoundException
 *             Indicates a class resolution issue
 */
protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    ois.defaultReadObject();
    final String memberDeclaringClassName = (String) ois.readObject();
    final String memberName = (String) ois.readObject();
    final String memberType = (String) ois.readObject();

    final Class memberDeclaringClass = Class.forName(memberDeclaringClassName, false,
            declaringType.getJavaType().getClassLoader());
    try {
        this.member = "method".equals(memberType)
                ? memberDeclaringClass.getMethod(memberName, ReflectHelper.NO_PARAM_SIGNATURE)
                : memberDeclaringClass.getField(memberName);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unable to locate member [" + memberDeclaringClassName + "#" + memberName + "]");
    }
}

From source file:com.microsoft.tfs.client.common.ui.framework.layout.GridDataBuilder.java

public GridDataBuilder vIndent(final int verticalIndent) {
    try {/*from   ww  w.j a v a2 s .  c o m*/
        final Class gdClass = gridData.getClass();
        final Field viField = gdClass.getField("verticalIndent"); //$NON-NLS-1$

        viField.setInt(gridData, verticalIndent);
    } catch (final Exception e) {
        // PRE SWT 3.1, ignore
    }

    return this;
}

From source file:com.he5ed.lib.cloudprovider.picker.CloudPickerActivity.java

/**
 * @hide//ww w . ja  v a2  s  . co  m
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cp_activity_picker);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    // lock right drawer from been swiped open
    drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setItemIconTintList(null); // remove the auto grey tint to keep icon color
    Menu menu = navigationView.getMenu();
    CloudProvider cloudProvider = CloudProvider.getInstance(this);
    // check whether individual account is assigned
    String accountId = getIntent().getStringExtra(EXTRA_PICK_ACCOUNT_ID);
    if (!TextUtils.isEmpty(accountId)) {
        mAccounts = new CloudAccount[1];
        mAccounts[0] = cloudProvider.getAccountById(accountId);
    } else {
        mAccounts = cloudProvider.getCloudAccounts();
    }
    // populate navigation menu
    for (int i = 0; i < mAccounts.length; i++) {
        CloudAccount account = mAccounts[i];
        MenuItem item = menu.add(0, i, 0, account.getUser().email);
        // use cloud API class reflection
        try {
            Class clazz = Class.forName(account.api);
            Field iconResource = clazz.getField("ICON_RESOURCE");
            item.setIcon(iconResource.getInt(null));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            item.setIcon(R.drawable.ic_cloud_black_24dp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        item.setCheckable(true);
    }

    mFragmentManager = getSupportFragmentManager();
    mItemFragment = (ItemFragment) mFragmentManager.findFragmentById(R.id.right_drawer_view);
    if (mItemFragment == null) {
        mItemFragment = new ItemFragment();
        mFragmentManager.beginTransaction().add(R.id.right_drawer_view, mItemFragment).commit();
    }

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mErrorView = (LinearLayout) findViewById(R.id.error_view);
    if (savedInstanceState != null) {
        switch (savedInstanceState.getInt("empty_view_visibility")) {
        case View.VISIBLE:
            mErrorView.setVisibility(View.VISIBLE);
            ImageView icon = (ImageView) mErrorView.findViewById(R.id.empty_icon_image_view);
            TextView title = (TextView) mErrorView.findViewById(R.id.empty_title_text_view);
            TextView detail = (TextView) mErrorView.findViewById(R.id.empty_detail_text_view);
            Bitmap bitmap = savedInstanceState.getParcelable("icon_drawable");
            icon.setImageBitmap(bitmap);
            title.setText(savedInstanceState.getCharSequence("title_text"));
            detail.setText(savedInstanceState.getCharSequence("detail_text"));
            break;
        case View.INVISIBLE:
            mErrorView.setVisibility(View.INVISIBLE);
            break;
        case View.GONE:
            mErrorView.setVisibility(View.GONE);
            break;
        }
    } else {
        // open drawer on first load
        drawer.openDrawer(GravityCompat.START);
    }
}

From source file:com.cloudant.mazha.HttpRequests.java

public String getUserAgent() {
    if (userAgent == null) {
        String ua = this.getUserAgentFromResource();
        if (Misc.isRunningOnAndroid()) {
            try {
                Class c = Class.forName("android.os.Build$VERSION");
                String codename = (String) c.getField("CODENAME").get(null);
                int sdkInt = c.getField("SDK_INT").getInt(null);
                userAgent = String.format("%s Android %s %d", ua, codename, sdkInt);
            } catch (Exception e) {
                userAgent = String.format("%s Android unknown version", ua);
            }/*from w  w  w . j a v a 2 s .  c o  m*/
        } else {
            userAgent = String.format("%s (%s; %s; %s)", ua, System.getProperty("os.arch"),
                    System.getProperty("os.name"), System.getProperty("os.version"));
        }
    }
    return userAgent;
}

From source file:org.comicwiki.ThingCache.java

protected final String readCompositePropertyKey(Subject subject, Thing object) throws NoSuchFieldException,
        SecurityException, IllegalArgumentException, IllegalAccessException, IllegalThingException {
    Class<?> clazz = object.getClass();
    if (subject.key().isEmpty()) {// composite
        StringBuilder sb = new StringBuilder();
        String[] keys = subject.compositeKey();

        for (String key : keys) {
            Field field = clazz.getField(key);
            field.setAccessible(true);/*w ww.j  a v a 2 s. c o m*/
            Object fieldValue = field.get(object);
            if (fieldValue == null) {
                continue;
            } else if (fieldValue instanceof String) {
                sb.append(field.getName()).append(":").append(fieldValue);
            } else if (fieldValue instanceof IRI) {
                Thing thing = instanceCache.get((IRI) fieldValue);
                String id = readCompositePropertyKey(thing);
                sb.append(id);
            }
            sb.append('_');
        }
        if (sb.length() > 0) {
            return hf.hashBytes((object.getClass().getCanonicalName() + ":" + sb.toString()).getBytes())
                    .toString();
            //   return DigestUtils.md5Hex();
        }
    } else {
        Field field = clazz.getField(subject.key());
        field.setAccessible(true);
        Object fieldValue = field.get(object);
        if (fieldValue instanceof String) {
            return DigestUtils.md5Hex((String) fieldValue);
        } else if (fieldValue == null) {
            return null;
        } else if (Thing.class.isAssignableFrom(fieldValue.getClass())) {
            return readCompositePropertyKey((Thing) fieldValue);
        }
    }
    LOG.warning("This class does not have a key assigned. Is it a blank node? " + clazz.getName());

    return null;
}

From source file:seava.j4e.presenter.service.ServiceLocator.java

@Override
public <M, F, P> IDsService<M, F, P> findDsService(Class<?> modelClass) throws Exception {
    return this.findDsService((String) modelClass.getField("ALIAS").get(null), this.getDsServiceFactories());
}

From source file:org.eclipse.emf.teneo.hibernate.EPackageConstructor.java

/**
 * Build a list of EPackages from the passed EcoreModelClasses.
 *///from   ww  w . j  av  a  2 s  .  co  m
private List<EPackage> buildFromModelClasses() {
    final ArrayList<EPackage> result = new ArrayList<EPackage>();
    for (String ecoreModelPackageClassName : ecoreModelClasses) {
        try {
            final Class<?> cls = this.getClass().getClassLoader().loadClass(ecoreModelPackageClassName);
            final EPackage emp;
            // handle the case that this is an EPackage interface
            if (cls.isInterface()) {
                final Field f = cls.getField("eINSTANCE");
                // purposely passing null because it must be static
                emp = (EPackage) f.get(null);
            } else {
                final Method m = cls.getMethod("init");
                // purposely passing null because it must be static
                emp = (EPackage) m.invoke(null);
            }

            // initialise the emp, will also read the epackage
            result.add(emp);
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Excption while trying to retrieve EcoreModelPackage instance from class: "
                            + ecoreModelPackageClassName,
                    e);
        }
    }
    return result;
}