java.lang.reflect.Field#getName ( )源码实例Demo

下面列出了java.lang.reflect.Field#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: java-tool   文件: ReflectionPropertyHandler.java
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();
}
 
源代码2 项目: BigApp_Discuz_Android   文件: ColumnUtils.java
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;
}
 
源代码3 项目: astor   文件: MockitoAnnotations.java
@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);
            }
        }
    }
}
 
源代码4 项目: Monocle   文件: LinuxInput.java
/**
 * 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();
}
 
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());
    }
}
 
源代码6 项目: jdk8u60   文件: GraphicsPrimitive.java
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()+"\"";
}
 
源代码7 项目: jdk8u-dev-jdk   文件: ObjectStreamClass.java
/**
 * 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();
        }
    }
}
 
源代码8 项目: Hangar   文件: IconPackHelper.java
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);
    }
}
 
源代码9 项目: carina   文件: ExtendedFieldDecorator.java
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);
}
 
源代码10 项目: TencentKona-8   文件: ObjectStreamField.java
/**
 * 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();
}
 
源代码11 项目: Mycat2   文件: ReflectionProvider.java
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());
        }
    }
}
 
源代码12 项目: everyone-java-blog   文件: ReflectUtils.java
/**
 * 获取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);
    }
}
 
源代码13 项目: jdk8u-jdk   文件: ObjectStreamClass.java
/**
 * 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();
        }
    }
}
 
源代码14 项目: JDKSourceCode1.8   文件: ObjectStreamField.java
ObjectStreamField(Field field) {
    this(field.getName(), field.getType());
    this.field = field;
}
 
源代码15 项目: seppb   文件: TestMissionServiceImpl.java
@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);
}
 
源代码16 项目: AndroidRipper   文件: Prefs.java
public static String fromArray (Field parameter, int index) {
	return parameter.getName() + "[" + index + "]";
}
 
源代码17 项目: firebase-android-sdk   文件: CustomClassMapper.java
private static String propertyName(Field field) {
  String annotatedName = annotatedName(field);
  return annotatedName != null ? annotatedName : field.getName();
}
 
源代码18 项目: groovy   文件: CachedField.java
public CachedField(Field field) {
    super (field.getName(), field.getType());
    this.cachedField = field;
}
 
源代码19 项目: openjdk-jdk9   文件: ObjectStreamClass.java
public MemberSignature(Field field) {
    member = field;
    name = field.getName();
    signature = getClassSignature(field.getType());
}
 
源代码20 项目: sailfish-core   文件: SessionStorage.java
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);
				}

			}

		}

	}