【发布时间】:2014-08-22 13:22:57
【问题描述】:
我有一个名为注解的 WsField。
WsField.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface WsField
{
String fieldName();
}
我在 MyPojo 类中使用了这个 WsField 注解。
MyPojo.java
public class MyPojo
{
@WsField(fieldName="Column1")
private String fullName;
public String getFullName()
{
return fullName;
}
public void setFullName(String fullName)
{
this.fullName = fullName;
}
}
我想在map方法中设置有WsField注解的字段的值。
WsMapper.java
public class WsMapper
{
public static void map(Object instance,String attributeName, Object value)
{
Class clsMeta = instance.getClass();
for (Field field : clsMeta.getFields())
{
if (field.isAnnotationPresent(WsField.class))
{
field.setAccessible(true);
String fieldName = field.getAnnotation(WsField.class).fieldName();
if (fieldName.contains(attributeName))
{
try
{
field.set(instance, value);
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
}
}
}
Application.java
import java.lang.reflect.Field;
public class Application
{
public static void main(String[] args)
{
MyPojo obj = new MyPojo();
WsMapper.map(obj,"Column1", "Test");
String fullName = obj.getFullName();
System.out.println(fullName);
}
}
如何将 MyPojo 对象作为对 map 方法的引用?
它在下面的代码中工作。
MyPojo obj2 = new MyPojo();
Class clsMeta = obj2.getClass();
String fieldName = "";
for (Field f : clsMeta.getDeclaredFields())
{
if (f.isAnnotationPresent(WsField.class))
{
f.setAccessible(true);
fieldName = f.getAnnotation(WsField.class).fieldName();
if (fieldName.contains("Column1"))
{
try
{
f.set(obj, "Test");
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
我不明白。有什么问题?
标签: java reflection methods mapping