java class<t> 报错t类型_java中的class<T>和 class<?>区别示例代码详解

? 表示不确定的java类型。

T 表示java类型。

K V 分别代表java键值中的Key Value。

E 代表Element。

Object跟这些东西代表的java类型有啥区别呢?

Object是所有类的根类,是具体的一个类,使用的时候可能是需要类型强制转换的,但是用T ?等这些的话,在实际用之前类型就已经确定了,不需要强制转换。

第一种是固定的一种泛型,第二种是只要是Object类的子类都可以,换言之,任何类都可以,因为Object是所有类的根基类

固定的泛型指类型是固定的,比如:Interge,String. 就是

这里?代表一个未知的类型,

但是,这个未知的类型实际上是Collection的一个子类,Collection是这个通配符的上限.

举个例子

class Test { }

其中,限定了构造此类实例的时候T是一个确定类型(具体类型),这个类型实现了Collection接口,

但是实现 Collection接口的类很多很多,如果针对每一种都要写出具体的子类类型,那也太麻烦了,干脆还不如用

Object通用一下。

extends Collection>其中,?是一个未知类型,是一个通配符泛型,这个类型是实现Collection接口即可。The method take(Animal) in the type Test is not applicable for the arguments (Demo)

The method take(Animal) in the type Test is not applicable for the arguments (Demo)

The method take(Animal) in the type Test is not applicable for the arguments (Demo)

public class Demo { private T ob; public T getOb() { return ob;

} public void setOb(T ob) { this.ob = ob;

} public Demo(T ob) { super(); this.ob = ob;

}

public void print(){

System.out.println("T的类型是:"+ob.getClass().getName());

}

}public Class resolveAlias(String string) {

try {

if (string == null) {

return null;

}

// issue #748

String key = string.toLowerCase(Locale.ENGLISH);

Class value;

if (TYPE_ALIASES.containsKey(key)) {

value = (Class) TYPE_ALIASES.get(key);

} else {

value = (Class) Resources.classForName(string);

}

return value;

} catch (ClassNotFoundException e) {

throw new TypeException("Could not resolve type alias '" + string + "'. Cause: " + e, e);

}

}public class Base {

private static Map> map = new HashMap<>();

static {

map.put("string", String.class);

map.put("integer", Integer.class);

}

@SuppressWarnings("unchecked")

public Class get(String str) {

return (Class) map.get(str);

}

@Test

public void t() throws IllegalAccessException, InstantiationException {

Base base = new Base();

Class string = base.get("string");

System.out.println(string);

}

}

以上就是java中的class和 class>区别示例代码详解的详细内容,更多请关注php中文网其它相关文章!

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值