下面列出了java.lang.reflect.Field#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
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;
}
@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);
}
}
}
}
/**
* 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());
}
}
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()+"\"";
}
/**
* 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();
}
}
}
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);
}
}
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);
}
/**
* 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();
}
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());
}
}
}
/**
* 获取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);
}
}
/**
* 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();
}
}
}
ObjectStreamField(Field field) {
this(field.getName(), field.getType());
this.field = field;
}
@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);
}
public static String fromArray (Field parameter, int index) {
return parameter.getName() + "[" + index + "]";
}
private static String propertyName(Field field) {
String annotatedName = annotatedName(field);
return annotatedName != null ? annotatedName : field.getName();
}
public CachedField(Field field) {
super (field.getName(), field.getType());
this.cachedField = field;
}
public MemberSignature(Field field) {
member = field;
name = field.getName();
signature = getClassSignature(field.getType());
}
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);
}
}
}
}