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.free.exception.ExceptionHelper.java

/**
 * <p>/*from  w  w w  .  jav a2  s  .co  m*/
 * Checks whether this <code>Throwable</code> class can store a cause.
 * </p>
 * <p/>
 * <p>
 * This method does <b>not</b> check whether it actually does store a cause.
 * <p>
 * 
 * @param throwable
 *          the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class<?> cls = throwable.getClass();
    for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
        try {
            Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[]) null);
            if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                return true;
            }
        } catch (NoSuchMethodException ignored) {
        } catch (SecurityException ignored) {
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
    } catch (SecurityException ignored) {
    }

    return false;
}

From source file:com.twosigma.beaker.sql.QueryExecutor.java

private Object getValue(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
    if (obj instanceof Map) {
        return ((Map) obj).get(fieldName);
    } else {/*from   w  ww  .jav  a  2 s  .  com*/
        Class<?> clazz = obj.getClass();
        Field field = clazz.getField(fieldName);
        return field.get(obj);
    }
}

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

public Object convertToTypedObject(Object source, Type type)
        throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException, InstantiationException {
    LOG.debug("convertToTypedObject(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 = (Object[]) source;

        List<Object> list = new ArrayList<Object>();

        for (Object component : components) {
            list.add(convertToTypedObject(component, listType.getElementType()));
        }/*from ww  w  . j av  a  2  s  .c om*/
        return list;
    } else if (type instanceof RecordType) {
        LOG.debug("Type is a Record(Map) Type");

        RecordType recordType = (RecordType) type;

        Class<?> recordClass = classLoader.loadClass(recordType);
        Map<String, Object> map = new HashMap<String, Object>();

        for (Entry<String, Type> entry : recordType.getFieldTypes().entrySet()) {
            Object fieldValue = recordClass.getField(entry.getKey()).get(source);
            map.put(entry.getKey(), convertToTypedObject(fieldValue, entry.getValue()));
        }
        return map;
    }
    LOG.error("Type is invalid");
    throw new InstantiationException();
}

From source file:com.gamethrive.GameThriveUnityProxy.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public GameThriveUnityProxy(String listenerName, String googleProjectNumber, String gameThriveAppId) {
    unitylistenerName = listenerName;// w w w.  j ava 2s  .co  m

    try {
        // We use reflection here so the default proguard config does not get an error for native apps.
        Class unityPlayerClass;
        unityPlayerClass = Class.forName("com.unity3d.player.UnityPlayer");
        unitySendMessage = unityPlayerClass.getMethod("UnitySendMessage", String.class, String.class,
                String.class);

        gameThrive = new GameThrive((Activity) unityPlayerClass.getField("currentActivity").get(null),
                googleProjectNumber, gameThriveAppId, this);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.googlecode.android_scripting.facade.ContactsFacade.java

public ContactsFacade(FacadeManager manager) {
    super(manager);
    mService = manager.getService();/* w w w  .  j a va 2 s  .c  o  m*/
    mContentResolver = mService.getContentResolver();
    mCommonIntentsFacade = manager.getReceiver(CommonIntentsFacade.class);
    try {
        // Backward compatibility... get contract stuff using reflection
        Class<?> phone = Class.forName("android.provider.ContactsContract$CommonDataKinds$Phone");
        mPhoneContent = (Uri) phone.getField("CONTENT_URI").get(null);
        mContactId = (String) phone.getField("CONTACT_ID").get(null);
        mPrimary = (String) phone.getField("IS_PRIMARY").get(null);
        mPhoneNumber = (String) phone.getField("NUMBER").get(null);
        mHasPhoneNumber = (String) phone.getField("HAS_PHONE_NUMBER").get(null);
    } catch (Exception e) {
    }
}

From source file:org.apache.servicecomb.swagger.generator.core.TestClassUtils.java

@Test
public void getOrCreateBodyClass() throws NoSuchFieldException {
    SwaggerGenerator generator = UnitTestSwaggerUtils.generateSwagger(Impl.class);
    OperationGenerator operationGenerator = generator.getOperationGeneratorMap().get("getUser");

    Class<?> cls = ClassUtils.getOrCreateBodyClass(operationGenerator, null);
    Assert.assertEquals("gen.swagger.getUserBody", cls.getName());
    Assert.assertEquals("java.util.List<java.lang.String>", cls.getField("p1").getGenericType().getTypeName());
    Assert.assertEquals("java.util.List<org.apache.servicecomb.foundation.test.scaffolding.model.User>",
            cls.getField("p2").getGenericType().getTypeName());
}

From source file:edu.pdx.its.portal.routelandia.DatePickUp.java

/**
 * change the minute interval to quarter*
 * @param timePicker : timepicker obk in the view
 *///from   ww  w.  ja  va2  s  . c  om
@SuppressLint("NewApi")
private void setTimePickerInterval(TimePicker timePicker) {
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");

        Field field = classForid.getField("minute");
        NumberPicker minutePicker = (NumberPicker) timePicker.findViewById(field.getInt(null));

        minutePicker.setMinValue(0);
        minutePicker.setMaxValue(7);
        ArrayList<String> displayedValues = new ArrayList<>();
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.vmware.photon.controller.housekeeper.xenon.HousekeeperServiceGroupTest.java

private String[] createServiceSelfLinks() {
    List<String> apiBackendServiceSelfLinks = new ArrayList<>();
    Set<Class<? extends Service>> set = ApiBackendFactory.FACTORY_SERVICES_MAP.keySet();
    for (Class cls : set) {
        try {//from   w  w  w  .  j  av a2s . c  o  m
            Field fld = cls.getField("FACTORY_LINK");
            apiBackendServiceSelfLinks.add((String) fld.get(null));
        } catch (IllegalAccessException | NoSuchFieldException e) {
            // Simply ignore them
        }
    }

    return ArrayUtils.addAll(apiBackendServiceSelfLinks.toArray(new String[0]), RootNamespaceService.SELF_LINK,
            ImageReplicatorServiceFactory.SELF_LINK, ImageCopyServiceFactory.SELF_LINK,
            ImageHostToHostCopyServiceFactory.SELF_LINK, ImageDatastoreSweeperServiceFactory.SELF_LINK,
            ImageCleanerServiceFactory.SELF_LINK, ImageSeederSyncServiceFactory.SELF_LINK,
            TaskSchedulerServiceFactory.SELF_LINK, TaskTriggerFactoryService.SELF_LINK,
            HousekeeperServiceGroup.getTriggerCleanerServiceUri(),
            HousekeeperServiceGroup.getImageSeederSyncTriggerServiceUri(),
            HousekeeperServiceGroup.IMAGE_COPY_SCHEDULER_SERVICE);
}

From source file:de.anderdonau.hackersdiet.MonthDetailFragment.java

/**
 * Search a widget by its name and return its ID.
 *//*from  ww  w  .  j av a2  s .  c o m*/
public int getIdByName(String name) {
    Class res = R.id.class;
    int id;
    try {
        Field field = res.getField(name);
        id = field.getInt(null);
    } catch (Exception e) {
        Log.d("getIdByName", "Cant get " + name);
        return -1;
    }
    return id;
}

From source file:com.android.build.gradle.internal.incremental.fixture.ClassEnhancement.java

private void patchClass(@NonNull String name, @Nullable String patch)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {

    Class<?> originalEnhancedClass = getClass().getClassLoader().loadClass(name);
    if (originalEnhancedClass.isInterface()) {
        // we don't patch interfaces.
        return;/*from w w  w . java 2s  .c om*/
    }
    Field newImplementationField = originalEnhancedClass.getField("$change");
    // class might not be accessible from there
    newImplementationField.setAccessible(true);

    if (patch == null) {
        // Revert to original implementation.
        newImplementationField.set(null, null);
        return;
    }

    Object change = mEnhancedClassLoaders.get(patch).loadClass(name + "$override").newInstance();

    newImplementationField.set(null, change);
}