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:com.paywith.ibeacon.service.IBeaconService.java

@Override
public void onCreate() {
    //Log.i(TAG, "iBeaconService version "+ BuildConfig.VERSION_NAME+" is starting up");
    getBluetoothAdapter();//from w  w  w. j  a v  a 2s  .  co m
    bluetoothCrashResolver = new BluetoothCrashResolver(this);
    bluetoothCrashResolver.start();

    setupApiConnection();

    // Look for simulated scan data
    try {
        Class klass = Class.forName("com.paywith.ibeacon.SimulatedScanData");
        java.lang.reflect.Field f = klass.getField("iBeacons");
        this.simulatedScanData = (List<IBeacon>) f.get(null);
    } catch (ClassNotFoundException e) {
        if (IBeaconManager.debug)
            Log.d(TAG, "No com.paywith.ibeacon.SimulatedScanData class exists.");
    } catch (Exception e) {
        Log.e(TAG,
                "Cannot get simulated Scan data.  Make sure your com.paywith.ibeacon.SimulatedScanData class defines a field with the signature 'public static List<IBeacon> iBeacons'",
                e);
    }

    IntentFilter theFilter = new IntentFilter();
    theFilter.addAction(Intent.ACTION_SCREEN_OFF);
    theFilter.addAction(Intent.ACTION_SCREEN_ON);
    this.context = this.getBaseContext();
    settings = context.getSharedPreferences(PREFERENCES, 0);
    editor = settings.edit();
}

From source file:org.kde.necessitas.ministro.ExtractStyle.java

private JSONObject getGradientDrawable(GradientDrawable drawable) {
    JSONObject json = new JSONObject();
    try {/*from w w  w  .  j a v  a 2s. c o m*/
        json.put("type", "gradient");
        Object obj = drawable.getConstantState();
        Class<?> gradientStateClass = obj.getClass();
        json.put("shape", gradientStateClass.getField("mShape").getInt(obj));
        json.put("gradient", gradientStateClass.getField("mGradient").getInt(obj));
        GradientDrawable.Orientation orientation = (Orientation) gradientStateClass.getField("mOrientation")
                .get(obj);
        json.put("orientation", orientation.name());
        int[] intArray = (int[]) gradientStateClass.getField("mColors").get(obj);
        json.put("colors", getJsonArray(intArray, 0, intArray.length));
        json.put("positions", getJsonArray((float[]) gradientStateClass.getField("mPositions").get(obj)));
        json.put("solidColor", gradientStateClass.getField("mSolidColor").getInt(obj));
        json.put("strokeWidth", gradientStateClass.getField("mStrokeWidth").getInt(obj));
        json.put("strokeColor", gradientStateClass.getField("mStrokeColor").getInt(obj));
        json.put("strokeDashWidth", gradientStateClass.getField("mStrokeDashWidth").getFloat(obj));
        json.put("strokeDashGap", gradientStateClass.getField("mStrokeDashGap").getFloat(obj));
        json.put("radius", gradientStateClass.getField("mRadius").getFloat(obj));
        float[] floatArray = (float[]) gradientStateClass.getField("mRadiusArray").get(obj);
        if (floatArray != null)
            json.put("radiusArray", getJsonArray(floatArray));
        Rect rc = (Rect) gradientStateClass.getField("mPadding").get(obj);
        if (rc != null)
            json.put("padding", getJsonRect(rc));
        json.put("width", gradientStateClass.getField("mWidth").getInt(obj));
        json.put("height", gradientStateClass.getField("mHeight").getInt(obj));
        json.put("innerRadiusRatio", gradientStateClass.getField("mInnerRadiusRatio").getFloat(obj));
        json.put("thicknessRatio", gradientStateClass.getField("mThicknessRatio").getFloat(obj));
        json.put("innerRadius", gradientStateClass.getField("mInnerRadius").getInt(obj));
        json.put("thickness", gradientStateClass.getField("mThickness").getInt(obj));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

From source file:com.sikulix.core.SX.java

private static void setOptions(PropertiesConfiguration someOptions) {
    if (isNull(someOptions) || someOptions.size() == 0) {
        return;/*from   w  w w.ja  v a 2 s .c om*/
    }
    Iterator<String> allKeys = someOptions.getKeys();
    List<String> sxSettings = new ArrayList<>();
    while (allKeys.hasNext()) {
        String key = allKeys.next();
        if (key.startsWith("Settings.")) {
            sxSettings.add(key);
            continue;
        }
        trace("!setOptions: %s = %s", key, someOptions.getProperty(key));
    }
    if (sxSettings.size() > 0) {
        Class cClass = null;
        try {
            cClass = Class.forName("org.sikuli.basics.Settings");
        } catch (ClassNotFoundException e) {
            error("!setOptions: %s", cClass);
        }
        if (!isNull(cClass)) {
            for (String sKey : sxSettings) {
                String sAttr = sKey.substring("Settings.".length());
                Field cField = null;
                Class ccField = null;
                try {
                    cField = cClass.getField(sAttr);
                    ccField = cField.getType();
                    if (ccField.getName() == "boolean") {
                        cField.setBoolean(null, someOptions.getBoolean(sKey));
                    } else if (ccField.getName() == "int") {
                        cField.setInt(null, someOptions.getInt(sKey));
                    } else if (ccField.getName() == "float") {
                        cField.setFloat(null, someOptions.getFloat(sKey));
                    } else if (ccField.getName() == "double") {
                        cField.setDouble(null, someOptions.getDouble(sKey));
                    } else if (ccField.getName() == "String") {
                        cField.set(null, someOptions.getString(sKey));
                    }
                    trace("!setOptions: %s = %s", sAttr, someOptions.getProperty(sKey));
                    someOptions.clearProperty(sKey);
                } catch (Exception ex) {
                    error("!setOptions: %s = %s", sKey, sxOptions.getProperty(sKey));
                }
            }
        }
    }
}

From source file:org.omnaest.utils.beans.BeanUtils.java

/**
 * Returns a {@link BeanPropertyAccessor} object determined for the given property name
 * /*ww w  .  j av  a2s  .c o  m*/
 * @see #beanPropertyAccessor(Class, Field)
 * @see #beanPropertyAccessorSet(Class)
 * @see #propertyNameToBeanPropertyAccessorMap(Class)
 * @param beanClass
 * @param propertyName
 * @return
 */
public static <B> BeanPropertyAccessor<B> beanPropertyAccessor(Class<B> beanClass, String propertyName) {
    //
    BeanPropertyAccessor<B> retval = null;

    //
    if (beanClass != null && propertyName != null) {
        //
        try {
            //
            Set<BeanMethodInformation> beanMethodInformationSet = BeanUtils
                    .propertyNameToBeanMethodInformationMap(beanClass).get(propertyName);

            //     
            Method methodGetter = null;
            Method methodSetter = null;
            for (BeanMethodInformation beanMethodInformation : beanMethodInformationSet) {
                if (beanMethodInformation.isGetter()) {
                    methodGetter = beanMethodInformation.getMethod();
                } else if (beanMethodInformation.isSetter()) {
                    methodSetter = beanMethodInformation.getMethod();
                }
            }

            //
            Field field = null;
            try {
                //
                field = beanClass.getDeclaredField(propertyName);
            } catch (Exception e) {
            }

            //
            if (field == null) {
                try {
                    //
                    field = beanClass.getField(propertyName);
                } catch (Exception e) {
                }
            }

            //
            retval = new BeanPropertyAccessor<B>(field, methodGetter, methodSetter, propertyName, beanClass);
        } catch (Exception e) {
        }
    }

    //
    return retval;
}

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java

private Object get(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException,
        InvocationTargetException, IllegalAccessException {
    Class oClass = nodeClass(node);
    if (oClass != null)
        obj = null;/*from ww  w  .j  av a  2s . c  o  m*/
    else
        oClass = obj.getClass();

    String name = node.getAttribute("name");
    String id = node.getAttribute("id");
    if (log.isDebugEnabled())
        log.debug("get " + name);

    try {
        // try calling a getXxx method.
        Method method = oClass.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1),
                (java.lang.Class[]) null);
        obj = method.invoke(obj, (java.lang.Object[]) null);
        configure(obj, node, 0);
    } catch (NoSuchMethodException nsme) {
        try {
            Field field = oClass.getField(name);
            obj = field.get(obj);
            configure(obj, node, 0);
        } catch (NoSuchFieldException nsfe) {
            throw nsme;
        }
    }
    if (id != null)
        _idMap.put(id, obj);
    return obj;
}

From source file:com.runye.express.chat.activity.ChatActivity.java

/**
 * ?gridview?view/* www.jav  a2 s .c  om*/
 * 
 * @param i
 * @return
 */
private View getGridChildView(int i) {
    View view = View.inflate(this, R.layout.chat_expression_gridview, null);
    ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
    List<String> list = new ArrayList<String>();
    if (i == 1) {
        List<String> list1 = reslist.subList(0, 20);
        list.addAll(list1);
    } else if (i == 2) {
        list.addAll(reslist.subList(20, reslist.size()));
    }
    list.add("delete_expression");
    final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
    gv.setAdapter(expressionAdapter);
    gv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String filename = expressionAdapter.getItem(position);
            try {
                // ????
                // ?????
                if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                    if (filename != "delete_expression") { // ?
                        // ????SmileUtils
                        Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        mEditTextContent
                                .append(SmileUtil.getSmiledText(ChatActivity.this, (String) field.get(null)));
                    } else { // 
                        if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                            int selectionStart = mEditTextContent.getSelectionStart();// ??
                            if (selectionStart > 0) {
                                String body = mEditTextContent.getText().toString();
                                String tempStr = body.substring(0, selectionStart);
                                int i = tempStr.lastIndexOf("[");// ???
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i, selectionStart);
                                    if (SmileUtil.containsKey(cs.toString()))
                                        mEditTextContent.getEditableText().delete(i, selectionStart);
                                    else
                                        mEditTextContent.getEditableText().delete(selectionStart - 1,
                                                selectionStart);
                                } else {
                                    mEditTextContent.getEditableText().delete(selectionStart - 1,
                                            selectionStart);
                                }
                            }
                        }

                    }
                }
            } catch (Exception e) {
            }

        }
    });
    return view;
}

From source file:com.kaixin.android.activity.ChatActivity.java

/**
 * ?gridview?view/*from  w w  w  .  java2  s.  c o m*/
 * 
 * @param i
 * @return
 */
private View getGridChildView(int i) {
    View view = View.inflate(this, R.layout.expression_gridview, null);
    ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
    List<String> list = new ArrayList<String>();
    if (i == 1) {
        List<String> list1 = reslist.subList(0, 20);
        list.addAll(list1);
    } else if (i == 2) {
        list.addAll(reslist.subList(20, reslist.size()));
    }
    list.add("delete_expression");
    final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
    gv.setAdapter(expressionAdapter);
    gv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String filename = expressionAdapter.getItem(position);
            try {
                // ????
                // ?????
                if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                    if (filename != "delete_expression") { // ?
                        Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        mEditTextContent
                                .append(SmileUtils.getSmiledText(ChatActivity.this, (String) field.get(null)));
                    } else { // 
                        if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                            int selectionStart = mEditTextContent.getSelectionStart();// ??
                            if (selectionStart > 0) {
                                String body = mEditTextContent.getText().toString();
                                String tempStr = body.substring(0, selectionStart);
                                int i = tempStr.lastIndexOf("[");// ???
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i, selectionStart);
                                    if (SmileUtils.containsKey(cs.toString()))
                                        mEditTextContent.getEditableText().delete(i, selectionStart);
                                    else
                                        mEditTextContent.getEditableText().delete(selectionStart - 1,
                                                selectionStart);
                                } else {
                                    mEditTextContent.getEditableText().delete(selectionStart - 1,
                                            selectionStart);
                                }
                            }
                        }

                    }
                }
            } catch (Exception e) {
            }

        }
    });
    return view;
}

From source file:pt.fct.di.benchmarks.TPCW_Riak.database.TPCW_Riak_Executor.java

private Entity insertOrModifyAttribute(Entity entity, Object value, String column, int writeConsistency)
        throws Exception {

    Class<? extends Entity> cls = entity.getClass();
    Field fld = cls.getField(column);
    fld.set(entity, value);//from w w  w  .  j a  v a2  s.c  o  m
    return entity;
}

From source file:org.apache.asterix.om.typecomputer.TypeComputerTest.java

private boolean testTypeComputer(Class<? extends IResultTypeComputer> c) throws Exception {
    // Mocks the type environment.
    IVariableTypeEnvironment mockTypeEnv = mock(IVariableTypeEnvironment.class);
    // Mocks the metadata provider.
    IMetadataProvider<?, ?> mockMetadataProvider = mock(IMetadataProvider.class);

    // Mocks function expression.
    AbstractFunctionCallExpression mockExpr = mock(AbstractFunctionCallExpression.class);

    // A function at most has six argument.
    List<Mutable<ILogicalExpression>> argRefs = new ArrayList<>();
    for (int argIndex = 0; argIndex < 6; ++argIndex) {
        ILogicalExpression mockArg = mock(ILogicalExpression.class);
        argRefs.add(new MutableObject<>(mockArg));
        when(mockTypeEnv.getType(mockArg)).thenReturn(BuiltinType.ANY);
    }//from   w ww  .  j a va2s . c o  m

    // Sets up arguments for the mocked expression.
    when(mockExpr.getArguments()).thenReturn(argRefs);

    // Sets up required/actual types of the mocked expression.
    Object[] opaqueParameters = new Object[2];
    opaqueParameters[0] = BuiltinType.ANY;
    opaqueParameters[1] = BuiltinType.ANY;
    when(mockExpr.getOpaqueParameters()).thenReturn(opaqueParameters);

    // Tests the return type. It should be either ANY or NULLABLE/MISSABLE.
    IResultTypeComputer instance = (IResultTypeComputer) c.getField("INSTANCE").get(null);
    IAType resultType = instance.computeType(mockExpr, mockTypeEnv, mockMetadataProvider);
    ATypeTag typeTag = resultType.getTypeTag();
    if (typeTag == ATypeTag.ANY) {
        return true;
    }
    if (typeTag == ATypeTag.UNION) {
        AUnionType unionType = (AUnionType) resultType;
        return unionType.isMissableType() && unionType.isNullableType();
    }
    return false;
}

From source file:org.apache.axis.encoding.DeserializationContext.java

/**
 * Convenience method to get the Deserializer for a specific
 * java class from its meta data./*from w w w.java2s .  c  om*/
 * @param cls is the Class used to find the deserializer
 * @return Deserializer
 */
public Deserializer getDeserializerForClass(Class cls) {
    if (cls == null) {
        cls = destClass;
    }
    if (cls == null) {
        return null;
    }
    //        if (cls.isArray()) {
    //            cls = cls.getComponentType();
    //        }
    if (javax.xml.rpc.holders.Holder.class.isAssignableFrom(cls)) {
        try {
            cls = cls.getField("value").getType();
        } catch (Exception e) {
        }
    }

    Deserializer dser = null;

    QName type = getTypeMapping().getTypeQName(cls);
    dser = getDeserializer(cls, type);
    if (dser != null)
        return dser;

    try {
        Method method = MethodCache.getInstance().getMethod(cls, DESERIALIZER_METHOD, DESERIALIZER_CLASSES);
        if (method != null) {
            TypeDesc typedesc = TypeDesc.getTypeDescForClass(cls);
            if (typedesc != null) {
                dser = (Deserializer) method.invoke(null,
                        new Object[] { getEncodingStyle(), cls, typedesc.getXmlType() });
            }
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("noDeser00", cls.getName()));
    }
    return dser;
}