Java Code Examples for java.lang.reflect.Field#getName()

The following examples show how to use java.lang.reflect.Field#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LinuxInput.java    From Monocle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert an event code to its equivalent string, given its type string.
 * The type string is needed because event codes are context sensitive. For
 * example, the code 1 is "SYN_CONFIG" for an EV_SYN event but "KEY_ESC" for
 * an EV_KEY event.  This method is inefficient and is for debugging use
 * only.
 */
static String codeToString(String type, short code) {
    int i = type.indexOf("_");
    if (i >= 0) {
        String prefix = type.substring(i + 1);
        String altPrefix = prefix.equals("KEY") ? "BTN" : prefix;
        for (Field field : LinuxInput.class.getDeclaredFields()) {
            String name = field.getName();
            try {
                if ((name.startsWith(prefix) || name.startsWith(altPrefix))
                        && field.getType() == Short.TYPE
                        && field.getShort(null) == code) {
                    return field.getName();
                }
            } catch (IllegalAccessException e) {
            }
        }
    }
    return new Formatter().format("0x%04x", code & 0xffff).out().toString();
}
 
Example 2
Source File: MockitoAnnotations.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
static void processAnnotationDeprecatedWay(AnnotationEngine annotationEngine, Object testClass, Field field) {
    boolean alreadyAssigned = false;
    for(Annotation annotation : field.getAnnotations()) {
        Object mock = annotationEngine.createMockFor(annotation, field);
        if (mock != null) {
            throwIfAlreadyAssigned(field, alreadyAssigned);
            alreadyAssigned = true;                
            try {
                new FieldSetter(testClass, field).set(mock);
            } catch (Exception e) {
                throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
                        + annotation, e);
            }
        }
    }
}
 
Example 3
Source File: ReflectionPropertyHandler.java    From java-tool with Apache License 2.0 6 votes vote down vote up
private void init(Class c, Method m, Field f) {
    E.illegalArgumentIf(null == m && null == f);
    this.entityClass = c;
    this.m = m;
    this.f = f;
    if (null != m) {
        this.mn = m.getName();
        this.propertyClass = m.getReturnType();
        if (void.class.equals(this.propertyClass)) {
            this.propertyClass = m.getParameterTypes()[0];
        }
    } else {
        this.fn = f.getName();
        this.propertyClass = f.getType();
    }
    this.propertyClassName = propertyClass.getName();
}
 
Example 4
Source File: ColumnUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static Method getColumnGetMethod(Class<?> entityType, Field field) {
    String fieldName = field.getName();
    Method getMethod = null;
    if (field.getType() == boolean.class) {
        getMethod = getBooleanColumnGetMethod(entityType, fieldName);
    }
    if (getMethod == null) {
        String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        try {
            getMethod = entityType.getDeclaredMethod(methodName);
        } catch (NoSuchMethodException e) {
            LogUtils.d(methodName + " not exist");
        }
    }

    if (getMethod == null && !Object.class.equals(entityType.getSuperclass())) {
        return getColumnGetMethod(entityType.getSuperclass(), field);
    }
    return getMethod;
}
 
Example 5
Source File: TestcontainersExtension.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static StoreAdapter getContainerInstance(final Object testInstance, final Field field) {
    try {
        field.setAccessible(true);
        Startable containerInstance = Preconditions.notNull((Startable) field.get(testInstance), "Container " + field.getName() + " needs to be initialized");
        return new StoreAdapter(field.getDeclaringClass(), field.getName(), containerInstance);
    } catch (IllegalAccessException e) {
        throw new ExtensionConfigurationException("Can not access container defined in field " + field.getName());
    }
}
 
Example 6
Source File: GraphicsPrimitive.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static String simplename(Field[] fields, Object o) {
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        try {
            if (o == f.get(null)) {
                return f.getName();
            }
        } catch (Exception e) {
        }
    }
    return "\""+o.toString()+"\"";
}
 
Example 7
Source File: ObjectStreamClass.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the serializable object fields of object obj using values from
 * array vals starting at offset 0.  The caller is responsible for
 * ensuring that obj is of the proper type; however, attempts to set a
 * field with a value of the wrong type will trigger an appropriate
 * ClassCastException.
 */
void setObjFieldValues(Object obj, Object[] vals) {
    if (obj == null) {
        throw new NullPointerException();
    }
    for (int i = numPrimFields; i < fields.length; i++) {
        long key = writeKeys[i];
        if (key == Unsafe.INVALID_FIELD_OFFSET) {
            continue;           // discard value
        }
        switch (typeCodes[i]) {
            case 'L':
            case '[':
                Object val = vals[offsets[i]];
                if (val != null &&
                    !types[i - numPrimFields].isInstance(val))
                {
                    Field f = fields[i].getField();
                    throw new ClassCastException(
                        "cannot assign instance of " +
                        val.getClass().getName() + " to field " +
                        f.getDeclaringClass().getName() + "." +
                        f.getName() + " of type " +
                        f.getType().getName() + " in instance of " +
                        obj.getClass().getName());
                }
                unsafe.putObject(obj, key, val);
                break;

            default:
                throw new InternalError();
        }
    }
}
 
Example 8
Source File: ObjectStreamClass.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the serializable object fields of object obj using values from
 * array vals starting at offset 0.  The caller is responsible for
 * ensuring that obj is of the proper type; however, attempts to set a
 * field with a value of the wrong type will trigger an appropriate
 * ClassCastException.
 */
void setObjFieldValues(Object obj, Object[] vals) {
    if (obj == null) {
        throw new NullPointerException();
    }
    for (int i = numPrimFields; i < fields.length; i++) {
        long key = writeKeys[i];
        if (key == Unsafe.INVALID_FIELD_OFFSET) {
            continue;           // discard value
        }
        switch (typeCodes[i]) {
            case 'L':
            case '[':
                Object val = vals[offsets[i]];
                if (val != null &&
                    !types[i - numPrimFields].isInstance(val))
                {
                    Field f = fields[i].getField();
                    throw new ClassCastException(
                        "cannot assign instance of " +
                        val.getClass().getName() + " to field " +
                        f.getDeclaringClass().getName() + "." +
                        f.getName() + " of type " +
                        f.getType().getName() + " in instance of " +
                        obj.getClass().getName());
                }
                unsafe.putObject(obj, key, val);
                break;

            default:
                throw new InternalError();
        }
    }
}
 
Example 9
Source File: IconPackHelper.java    From Hangar with GNU General Public License v3.0 5 votes vote down vote up
private static void loadApplicationResources(Context context,
        Map<String, String> iconPackResources, String packageName) {
    Field[] drawableItems;
    try {
        Context appContext = context.createPackageContext(packageName,
                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
        drawableItems = Class.forName(packageName+".R$drawable",
                true, appContext.getClassLoader()).getFields();
    } catch (Exception e){
        return;
    }

    for (Field f : drawableItems) {
        String name = f.getName();

        String icon = name.toLowerCase(Locale.getDefault());
        name = name.replaceAll("_", ".");

        iconPackResources.put(name, icon);

        int activityIndex = name.lastIndexOf(".");
        if (activityIndex <= 0 || activityIndex == name.length() - 1) {
            continue;
        }

        String iconPackage = name.substring(0, activityIndex);
        if (TextUtils.isEmpty(iconPackage)) {
            continue;
        }
        iconPackResources.put(iconPackage, icon);

        String iconActivity = name.substring(activityIndex + 1);
        if (TextUtils.isEmpty(iconActivity)) {
            continue;
        }
        iconPackResources.put(iconPackage + "." + iconActivity, icon);
    }
}
 
Example 10
Source File: ReflectUtils.java    From everyone-java-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 获取getter方法
 *
 * @param clazz
 * @param field
 * @return
 */
static Method getSetterMethod(Class<?> clazz, Field field) {
    String fieldName = field.getName();
    String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    try {
        return getInheritMethod(clazz, methodName, new Class<?>[]{field.getType()});
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: ReflectionProvider.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void validateFieldAccess(Field field) {
    if (Modifier.isFinal(field.getModifiers())) {
        if (JVMInfo.is15()) {
            field.setAccessible(true);
        } else {
            throw new ObjectAccessException("Invalid final field " + field.getDeclaringClass().getName() + "."
                    + field.getName());
        }
    }
}
 
Example 12
Source File: ExtendedFieldDecorator.java    From carina with Apache License 2.0 5 votes vote down vote up
protected ExtendedWebElement proxyForLocator(ClassLoader loader, Field field, ElementLocator locator) {
    InvocationHandler handler = new LocatingElementHandler(locator);
    WebElement proxy = (WebElement) Proxy.newProxyInstance(loader, new Class[] { WebElement.class, WrapsElement.class, Locatable.class },
            handler);
    return new ExtendedWebElement(proxy, field.getName(),
            field.isAnnotationPresent(FindBy.class) || field.isAnnotationPresent(ExtendedFindBy.class)? new LocalizedAnnotations(field).buildBy() : null);
}
 
Example 13
Source File: ObjectStreamField.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an ObjectStreamField representing the given field with the
 * specified unshared setting.  For compatibility with the behavior of
 * earlier serialization implementations, a "showType" parameter is
 * necessary to govern whether or not a getType() call on this
 * ObjectStreamField (if non-primitive) will return Object.class (as
 * opposed to a more specific reference type).
 */
ObjectStreamField(Field field, boolean unshared, boolean showType) {
    this.field = field;
    this.unshared = unshared;
    name = field.getName();
    Class<?> ftype = field.getType();
    type = (showType || ftype.isPrimitive()) ? ftype : Object.class;
    signature = getClassSignature(ftype).intern();
}
 
Example 14
Source File: CachedField.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CachedField(Field field) {
    super (field.getName(), field.getType());
    this.cachedField = field;
}
 
Example 15
Source File: ObjectStreamClass.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public MemberSignature(Field field) {
    member = field;
    name = field.getName();
    signature = getClassSignature(field.getType());
}
 
Example 16
Source File: ObjectStreamField.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
ObjectStreamField(Field field) {
    this(field.getName(), field.getType());
    this.field = field;
}
 
Example 17
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private static String propertyName(Field field) {
  String annotatedName = annotatedName(field);
  return annotatedName != null ? annotatedName : field.getName();
}
 
Example 18
Source File: Prefs.java    From AndroidRipper with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String fromArray (Field parameter, int index) {
	return parameter.getName() + "[" + index + "]";
}
 
Example 19
Source File: TestMissionServiceImpl.java    From seppb with MIT License 4 votes vote down vote up
@Override
public int testMissionUpdate(TestMission testMission) throws IllegalAccessException {
	int productId = ParameterThreadLocal.getProductId();
	int userId = ParameterThreadLocal.getUserId();

	Map<String, Object> queryOld = new HashMap<>();
	queryOld.put(CommonParameter.ID, testMission.getId());
	queryOld.put(CommonParameter.PRODUCT_ID, productId);
	TestMission oldTestMission = testMissionDAO.testMissionQuery(queryOld).get(0);

	testMission.setReqId(oldTestMission.getReqId());
	testMission.setType(oldTestMission.getType());
	testMission.setSpliter(oldTestMission.getSpliter());
	testMission.setSplitDate(oldTestMission.getSplitDate());

	String reqSum = "【#" + oldTestMission.getReqId() + " - " + oldTestMission.getReqSummary() + "】";
	String msg = "需求" + reqSum + "下的【" + oldTestMission.getTypeName() + "】任务,内容信息被修改";

	List<Integer> messageToSub = new ArrayList<>();
	messageToSub.add(oldTestMission.getSpliter());

	Message message = new Message();
	message.setProductId(productId);
	message.setObjectType(18);
	message.setObjectId(testMission.getId());
	message.setTitle("测试任务信息修改提示");
	message.setContent(msg);
	messageService.businessMessageGenerator(message, userId, messageToSub);

	if (oldTestMission.getResponser() - testMission.getResponser() != 0) {
		if (testMission.getResponser() - testMission.getSpliter() != 0) { //非测试计划负责人本人操作
			List<Integer> messageToResNew = new ArrayList<>();
			messageToResNew.add(testMission.getResponser());
			message.setContent(msg);
			messageService.businessMessageGenerator(message, userId, messageToResNew);
		}
		if (oldTestMission.getResponser() - oldTestMission.getSpliter() != 0) { //非测试计划负责人本人操作
			List<Integer> messageToResOld = new ArrayList<>();
			messageToResOld.add(oldTestMission.getResponser());
			String suffix = ",并且转交给他人负责跟进";
			message.setContent(msg + suffix);
			messageService.businessMessageGenerator(message, userId, messageToResOld);
		}
	} else {
		if (oldTestMission.getResponser() - oldTestMission.getSpliter() != 0) { //非测试计划负责人本人操作
			List<Integer> messageToRes = new ArrayList<>();
			messageToRes.add(oldTestMission.getResponser());
			message.setContent(msg);
			messageService.businessMessageGenerator(message, userId, messageToRes);
		}
	}

	List<SEPPHistory> histories = new ArrayList<>();
	Class<? extends TestMission> cls = testMission.getClass();
	Field[] fields = cls.getDeclaredFields();
	for (int i = 0; i < fields.length; i++) {
		Field field = fields[i];
		field.setAccessible(true);
		String keyName = field.getName();
		Object newValue = field.get(testMission);
		Object oldValue = field.get(oldTestMission);

		if (keyName.endsWith("Name") || keyName.equals("reqSummary")) {
			continue;
		}

		if (!Objects.equals(newValue, oldValue)) {
			SEPPHistory history = new SEPPHistory();
			history.setObjType(18);
			history.setObjId(testMission.getId());
			history.setProductId(productId);
			history.setOperUser(userId);
			history.setOperType(2);
			history.setOperComment(msg);
			history.setReferUser(oldTestMission.getResponser());
			history.setOrgValue(String.valueOf(oldValue));
			history.setNewValue(String.valueOf(newValue));
			history.setObjKey(keyName);
			histories.add(history);
		}
	}
	if (histories.size() > 0) {
		historyService.historyInsertBatch(histories);
	}

	return testMissionDAO.testMissionUpdate(testMission);
}
 
Example 20
Source File: SessionStorage.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
public void saveStateOfAnnotatedBean(Object bean) {

		String className = bean.getClass().getSimpleName();

        for (Field f : getAllObjectFields(bean)) {

			if (f.isAnnotationPresent(SessionStored.class)) {

				String fieldName = f.getName();

				Annotation annotation = f.getAnnotation(SessionStored.class);
				SessionStored ssAnotation = (SessionStored) annotation;

				try {

					f.setAccessible(true);

					Object value = f.get(bean);

					if(value != null) {

						String storageKey = className + "." + fieldName;

						if(!ssAnotation.cloneBySerialization()) {
                            storage.put(storageKey, value);
						} else {
							logger.debug("Cloned");
                            storage.put(storageKey, cloneBySerialization((Serializable)value));
						}

						logger.debug("Value stored {}", storageKey);

					}

				} catch (Exception e) {
					logger.error("Could not access value of field {} of class {}", fieldName, className, e);
				}

			}

		}

	}