Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.canappi.connector.yp.yhere.RepairView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, extras.getString(value));
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from w w w . j  a  v a2 s  .  c  o m
            } catch (NoSuchFieldException 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();
            }
        }
    } else {

    }

    repairViewIds = new HashMap();
    repairViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}

From source file:com.canappi.connector.yp.yhere.RestaurantView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, extras.getString(value));
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//w  w  w. j a  v a2 s  .co m
            } catch (NoSuchFieldException 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();
            }
        }
    } else {

    }

    restaurantViewIds = new HashMap();
    restaurantViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}

From source file:com.canappi.connector.yp.yhere.TheaterView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, extras.getString(value));
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from w ww.jav a  2 s  .  c  o  m
            } catch (NoSuchFieldException 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();
            }
        }
    } else {

    }

    theaterViewIds = new HashMap();
    theaterViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}

From source file:com.intel.moe.frameworks.inapppurchase.android.util.IabHelper.java

/**
 * Handles an activity result that's part of the purchase flow in in-app billing. If you
 * are calling {@link #launchPurchaseFlow}, then you must call this method from your
 * Activity's {@link Activity@onActivityResult} method. This method
 * MUST be called from the UI thread of the Activity.
 *
 * @param requestCode The requestCode as you received it.
 * @param resultCode The resultCode as you received it.
 * @param data The data (Intent) as you received it.
 * @return Returns true if the result was related to a purchase flow and was handled;
 *     false if the result was not related to a purchase, in which case you should
 *     handle it normally.//from ww  w.ja va 2 s.c o m
 */
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
    IabResult result;
    if (requestCode != mRequestCode)
        return false;

    checkNotDisposed();
    checkSetupDone("handleActivityResult");

    // end of async purchase operation that started on launchPurchaseFlow
    flagEndAsync();

    if (data == null) {
        logError("Null data in IAB activity result.");
        result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
        if (mPurchaseListener != null)
            mPurchaseListener.onIabPurchaseFinished(result, null);
        return true;
    }

    int responseCode = getResponseCodeFromIntent(data);
    String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
    String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);

    try {
        Class activityClass = Class.forName("android.app.Activity");

        if (resultCode == Integer.valueOf(activityClass.getDeclaredField("RESULT_OK").get(null).toString())
                && responseCode == BILLING_RESPONSE_RESULT_OK) {
            logDebug("Successful resultcode from purchase activity.");
            logDebug("Purchase data: " + purchaseData);
            logDebug("Data signature: " + dataSignature);
            logDebug("Extras: " + data.getExtras());
            logDebug("Expected item type: " + mPurchasingItemType);

            if (purchaseData == null || dataSignature == null) {
                logError("BUG: either purchaseData or dataSignature is null.");
                logDebug("Extras: " + data.getExtras().toString());
                result = new IabResult(IABHELPER_UNKNOWN_ERROR,
                        "IAB returned null purchaseData or dataSignature");
                if (mPurchaseListener != null)
                    mPurchaseListener.onIabPurchaseFinished(result, null);
                return true;
            }

            Purchase purchase = null;
            try {
                purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
                String sku = purchase.getSku();

                // Verify signature
                if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
                    logError("Purchase signature verification FAILED for sku " + sku);
                    result = new IabResult(IABHELPER_VERIFICATION_FAILED,
                            "Signature verification failed for sku " + sku);
                    if (mPurchaseListener != null)
                        mPurchaseListener.onIabPurchaseFinished(result, purchase);
                    return true;
                }
                logDebug("Purchase signature successfully verified.");
            } catch (JSONException e) {
                logError("Failed to parse purchase data.");
                e.printStackTrace();
                result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
                if (mPurchaseListener != null)
                    mPurchaseListener.onIabPurchaseFinished(result, null);
                return true;
            }

            if (mPurchaseListener != null) {
                mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"),
                        purchase);
            }
        } else if (resultCode == Integer
                .valueOf(activityClass.getDeclaredField("RESULT_OK").get(null).toString())) {
            // result code was OK, but in-app billing response was not OK.
            logDebug("Result code was OK but in-app billing response was not OK: "
                    + getResponseDesc(responseCode));
            if (mPurchaseListener != null) {
                result = new IabResult(responseCode, "Problem purchashing item.");
                mPurchaseListener.onIabPurchaseFinished(result, null);
            }
        } else if (resultCode == Integer
                .valueOf(activityClass.getDeclaredField("RESULT_CANCELED").get(null).toString())) {
            logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
            result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
            if (mPurchaseListener != null)
                mPurchaseListener.onIabPurchaseFinished(result, null);
        } else {
            logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: "
                    + getResponseDesc(responseCode));
            result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
            if (mPurchaseListener != null)
                mPurchaseListener.onIabPurchaseFinished(result, null);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:com.haulmont.cuba.core.global.MetadataTools.java

/**
 * Determine whether the given annotation is present in the object's class or in any of its superclasses.
 *
 * @param javaClass       entity class//from  w  w  w. j a v  a 2s.  c om
 * @param property        property name
 * @param annotationClass annotation class
 * @return
 */
public boolean isAnnotationPresent(Class javaClass, String property,
        Class<? extends Annotation> annotationClass) {
    Field field;
    try {
        field = javaClass.getDeclaredField(property);
        return field.isAnnotationPresent(annotationClass);
    } catch (NoSuchFieldException e) {
        Class superclass = javaClass.getSuperclass();
        while (superclass != null) {
            try {
                field = superclass.getDeclaredField(property);
                return field.isAnnotationPresent(annotationClass);
            } catch (NoSuchFieldException e1) {
                superclass = superclass.getSuperclass();
            }
        }
        throw new RuntimeException("Property not found: " + property);
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().// www .  j a v  a2s .  com
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance");
            Object object = method.invoke(null);

            File file = new File(current, clazz.getName() + ".ser");
            boolean created = file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        @SuppressWarnings("Convert2Diamond")
        List<String> fieldList = new ArrayList<>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:com.atlassian.jira.functest.framework.AdministrationImpl.java

private void reflectivlySetField(final Object self, Class<?> clazz, final String fieldName,
        final Object fieldValue) {
    Preconditions.checkNotNull(self, "cannot set field %s to %s on null object", fieldName, fieldValue);
    Field field = null;//from  w  w  w.ja v a 2s . c  om
    try {
        field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(self, fieldValue);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format(
                "Error setting field '%s' to '%s' for %s : possibly a security manager has prevented access to this field",
                fieldName, fieldValue, clazz.getName()), e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(String.format(
                "Error setting field '%s' to '%s' for %s : possibly a library update has changed this field",
                fieldName, fieldValue, clazz.getName()), e);
    } finally {
        if (field != null) {
            field.setAccessible(false);
        }
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from   w w  w .  ja  v a  2 s . c  o m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance", new Class[0]);
            Object object = method.invoke(null, new Object[0]);

            File file = new File(current, clazz.getName() + ".ser");
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        List<String> fieldList = new ArrayList<String>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private <T> Field findPropertyFieldExactUncached(Class<T> classType, String propName) {
    for (Field field : classType.getDeclaredFields()) {
        XmlElement xmlElement = field.getAnnotation(XmlElement.class);
        if (xmlElement != null && xmlElement.name() != null && xmlElement.name().equals(propName)) {
            return field;
        }//from  ww w.  j a v a  2  s  . c o m
        XmlAttribute xmlAttribute = field.getAnnotation(XmlAttribute.class);
        if (xmlAttribute != null && xmlAttribute.name() != null && xmlAttribute.name().equals(propName)) {
            return field;
        }
    }
    try {
        return classType.getDeclaredField(propName);
    } catch (NoSuchFieldException e) {
        // nothing found
    }
    Class<? super T> superclass = classType.getSuperclass();
    if (superclass.equals(Object.class)) {
        return null;
    }
    return findPropertyField(superclass, propName);
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

/**
 * Retrieves a {@link Field} instance declared by the specified class with
 * the specified name. Java access modifiers are ignored during this
 * retrieval. No guarantee is made as to whether the field returned will be
 * an instance or static field.// www  .ja  va2s  .  c om
 * <p>
 * A global caching mechanism within this class is used to store fields.
 * Combined with synchronization, this guarantees that no field will be
 * reflectively looked up twice.
 * </p>
 * <p>
 * If a field is deemed suitable for return,
 * {@link Field#setAccessible(boolean) setAccessible} will be invoked with
 * an argument of {@code true} before it is returned. This ensures that
 * callers do not have to check or worry about Java access modifiers when
 * dealing with the returned instance.
 * </p>
 *
 * @param clazz The class which contains the field to retrieve.
 * @param name The declared name of the field in the class.
 * @return A field object with the specified name declared by the specified
 * class.
 * @see Class#getDeclaredField(String)
 */
public synchronized static Field getField(Class<?> clazz, String name) {
    Map<String, Field> loaded;
    if (!_loadedFields.containsKey(clazz)) {
        loaded = new HashMap<>();
        _loadedFields.put(clazz, loaded);
    } else {
        loaded = _loadedFields.get(clazz);
    }
    if (loaded.containsKey(name)) {
        // If the field is loaded (or cached as not existing), return the relevant value, which might be null
        return loaded.get(name);
    }
    try {
        Field field = clazz.getDeclaredField(name);
        field.setAccessible(true);
        loaded.put(name, field);
        return field;
    } catch (Exception e) {
        // Error loading
        e.printStackTrace();
        // Cache field as not existing
        loaded.put(name, null);
        return null;
    }
}