问题
我在Eclipse中收到一个错误,声明我对Field.get(Object)的调用有一个未处理的异常。当我将代码包装在推荐的“尝试-捕捉”中时,错误将持续存在。我假设我必须在get()方法中用try-catch包装这个参数。这个是可能的吗?
错误
Unhandled exception type IllegalAccessException
所涉线路:
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());代码
Main.java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Entity> entities = Arrays.asList(
new Item(0, "Apple"),
new Item(1, "Banana"),
new Item(2, "Grape"),
new Item(3, "Orange")
);
List<Long> ids = null;
try {
ids = pluck("id", Long.class, entities, Entity.class, true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(ids);
}
public static <E extends Entity> List<Long> pluckIds(List<E> list) {
return list.stream().map(e -> e.getId()).collect(Collectors.toList());
}
public static <T,F> List<F> pluck(String fieldName, Class<F> fieldType,
List<T> list, Class<T> listType, boolean useLambda)
throws NoSuchFieldException, IllegalAccessException,
IllegalArgumentException {
Field f = listType.getDeclaredField(fieldName);
f.setAccessible(true);
if (useLambda) {
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
} else {
List<F> result = new ArrayList<F>();
for (T element : list) {
result.add(fieldType.cast(f.get(element)));
}
return result;
}
}
}Item.java
public class Item extends Entity {
private String name;
public Item(long id, String name) {
super(id);
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}Entity.java
public abstract class Entity {
private long id;
public Entity(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}发布于 2014-12-19 19:27:02
Eclipse现在有点愚蠢(可能有一个bug正在打开)。
这里有一个lambda表达式
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());Field#get(Object)被声明为引发已检查的异常。但是您正在实现的函数接口方法Function#apply(Object)没有实现。Eclipse很愚蠢,因为它建议您将语句包装在try块中,但是它会在整个过程中添加try块。
try {
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
} catch (Exception e) {
}实际上,它应该将它添加到lambda的主体中。
return list.stream().map(e -> {
try {
return fieldType.cast(f.get(e));
} catch (Exception e) {
return /* something else */ null; // or throw an unchecked exception
}
}).collect(Collectors.toList());当您的lambda身体是一个简单的表达式而不是块时,就会发生这种情况。
发布于 2014-12-19 19:25:47
您需要处理IllegalAccessException,它可以作为fieldType.cast(f.get(e))的结果抛出。您可以在try/catch中包围代码。
if (useLambda) {
return list.stream().map(e -> {
try {
return fieldType.cast(f.get(e));
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return null;
}
}).collect(Collectors.toList());
} https://stackoverflow.com/questions/27572594
复制相似问题