我有;
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
Run Code Online (Sandbox Code Playgroud)
是否有(简单)方法来检索列表的泛型类型?
我已经阅读过Neal Gafter关于这个主题的博客,但我仍然不清楚其中的一些观点.
为什么在给定Java的当前状态,JVM和现有集合API的情况下,不可能创建保留类型信息的Collections API的实现?难道这些不能以保留向后兼容性的方式替换未来Java版本中的现有实现吗?
举个例子:
List<T> list = REIList<T>(T.Class);
Run Code Online (Sandbox Code Playgroud)
REIList是这样的:
public REIList<T>() implements List {
private Object o;
private Class klass;
public REIList(Object o) {
this.o = o;
klass = o.getClass();
}
... the rest of the list implementation ...
Run Code Online (Sandbox Code Playgroud)
并且这些方法使用Object o和Class klass来获取类型信息.
为什么保留泛型类信息需要语言更改而不仅仅是JVM实现更改?
我不明白的是什么?
假设我有以下课程:
public class Test<E> {
public boolean sameClassAs(Object o) {
// TODO help!
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么检查那o是同一个班级E?
Test<String> test = new Test<String>();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;
Run Code Online (Sandbox Code Playgroud)
我无法更改方法签名,(Object o)因为我覆盖了超类,所以不要选择我的方法签名.
我也宁愿不去尝试一个演员然后如果失败就抓住结果异常.
我有一个类:
public abstract class BaseDao<T extends PersistentObject> {
protected Class<T> getClazz() {
return T.class;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是编译器说T.class;:Illegal class literal for the type parameter T.
我怎样才能上课T?
这是我的代码:ExecutorImp扩展了AbstractExecutor,它提取了与其实现者相同的执行逻辑(ExecutorImp就是一例),当调用ExecutorImp的execute()方法时,它将调用其超类型中的方法,但是超类型(AbstractExcutor) )应该知道另一个绑定到实现者的类(在示例中,它是User类):
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
abstract class AbstractExecutor<E> {
public void execute() throws Exception {
ArrayList<E> list = new ArrayList<E>();
// here I want to get the real type of 'E'
Class cl = this.getClass().getTypeParameters()[0].getGenericDeclaration().getClass();
Object o = cl.getConstructor(String.class).newInstance("Gate");
list.add((E) o);
System.out.println(format(list));
}
public abstract String format(ArrayList<E> list);
public abstract String getType();
}
public class ExectorImp<E> extends AbstractExecutor<User> {
@Override
public String getType() {
return "user";
}
@Override
public String format(ArrayList<User> list) {
StringBuffer sb = new StringBuffer();
for …Run Code Online (Sandbox Code Playgroud) 我想为IBatis创建一个基于枚举的通用映射器.我正在使用以下代码执行此操作.这确实有编译时错误,我不知道如何修复.也许我的解决方案是完全错误的(请记住使用IBatis),在这种情况下请提出更好的建议.
任何帮助赞赏.
我想要实现的是将后续的映射器定义为:
public class XEnumTypeHandler extends CommonEnumTypeHandler<X> {
}
Run Code Online (Sandbox Code Playgroud)
目前的代码:
public class CommonEnumTypeHandler<T extends Enum> implements TypeHandlerCallback {
public void setParameter(ParameterSetter ps, Object o) throws SQLException {
if (o.getClass().isAssignableFrom(**T**)) {
ps.setString(((**T**) o).value().toUpperCase());
} else
throw new SQLException("Excpected ParameterType object than: " + o);
}
public Object getResult(ResultGetter rs) throws SQLException {
Object o = valueOf(rs.getString());
if (o == null)
throw new SQLException("Unknown parameter type: " + rs.getString());
return o;
}
public Object valueOf(String s) {
for (T pt : …Run Code Online (Sandbox Code Playgroud) 当涉及没有泛型的类时,我可以像这样访问这个.class属性:
class Foo{
Class<Foo> getMyClass(){
return Foo.class;
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果Foo有一个泛型,我如何访问这个".class"属性?像这样:
class Foo<T>{
Class<Foo<T>> getMyClass(){
return (Foo<T>).class //this doesnt work...
}
}
Run Code Online (Sandbox Code Playgroud)
我试图回来Foo.class,但这不会起作用:"cannot cast from Class<Foo> to Class<Foo<T>>".
我怎样才能Foo<T>上课?
我想编写C#代码的等效Java代码.
我的C#代码如下:
public abstract class A<T> where T : A<T>, new()
{
public static void Process()
{
Process(new T());
}
public static void Process(T t)
{
// Do Something...
}
}
public class B : A<B>
{
}
public class C : A<C>
{
}
Run Code Online (Sandbox Code Playgroud)
Java代码与我的代码相似.
public abstract class A<T extends A<T>>
{
public static <T extends A<T>> void process()
{
process(new T()); // Error: Cannot instantiate the type T
}
public static <T extends A<T>> void process(T t)
{ …Run Code Online (Sandbox Code Playgroud) 所以我有一些'经理'类,例如GroupManager.所有这些经理都是单身人士.
使用此方法进行实例化:
private static GroupManager groupManager = null;
private GroupManager()
{
}
public static GroupManager Instance()
{
if (groupManager == null)
{
groupManager = new GroupManager();
}
return groupManager;
}
Run Code Online (Sandbox Code Playgroud)
我想我应该开始使用一些继承,因为他们有很多复制的方法.
每个Manager的Instance()方法都是相同的.
所以对于继承我可以这样做(显然):
GroupManager extends Manager
Run Code Online (Sandbox Code Playgroud)
是否可以使用泛型对所有管理器使用相同的Instance方法,例如:
public class Manager<E>
{
private static E instance = null;
public static E Instance()
{
if (instance == null)
{
instance = new E();
}
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这是有道理的:)
那么你就像普通的那样做GroupManager.Instance().
考虑这个HashMap扩展(如果它为null,则在调用"get"时生成V类的实例)
public class HashMapSafe<K, V> extends HashMap<K, V> implements Map<K, V>{
private Class<V> dataType;
public HashMapSafe(Class<V> clazz){
dataType = clazz;
}
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
if(!containsKey(key)){
try {
put((K)key, dataType.newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.get(key);
}
}
Run Code Online (Sandbox Code Playgroud)
它的用法是这样的
Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class);
sections.get(sectionName); //always returns a Section instance, existing or new
Run Code Online (Sandbox Code Playgroud)
在我看来,两次提供"部分"一次多余,一次作为通用类型,并且还提供它的类.我认为这是不可能的,但是有没有实现HashMapSafe,(保持相同的功能)所以它可以像这样使用?
Map<String,Section> sections = …Run Code Online (Sandbox Code Playgroud) 在C#中,我可以对泛型参数设置类型约束,该参数要求泛型类型具有默认的无参数构造函数.我可以用Java做同样的事吗?
在C#中:
public static T SomeMethodThatDoesSomeStuff<T>() where T : class, new()
{
// ... method body ...
}
Run Code Online (Sandbox Code Playgroud)
class和new()约束意味着T必须是可以使用零参数的new运算符调用的类.我对Java泛型的了解很少,我可以extends用来命名一个必需的超类.我可以使用它(或任何其他支持的操作)来实现上述功能吗?
当我运行以下代码时:
class MyStack<T>
{
private T[] stack;
... private T top;
private static final int size=50;
public MyStack()
{
stack = new int[size];
top = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
MyStack.java:18: generic array creation
stack = new T[size];
...
1 error
Run Code Online (Sandbox Code Playgroud)
什么应该是正确的代码,所以我不会得到这个错误
java ×12
generics ×11
inheritance ×2
c# ×1
collections ×1
dao ×1
enums ×1
jpa ×1
jvm ×1
reflection ×1
reification ×1
singleton ×1
stack ×1
static ×1