美文网首页
深入理解Java中的泛型(四)泛型方法的创建以及类型推断

深入理解Java中的泛型(四)泛型方法的创建以及类型推断

作者: 不思进取的码农 | 来源:发表于2021-08-31 18:54 被阅读0次

    泛型方法

    泛型方法的误区

    public T getValue2(){
        return value2;
    }
    

    很多人认为上述代码是个泛型方法 其实不是的,作为一个Android开发者我们有一个最常见的泛型方法findViewById

     @Nullable
     public final <T extends View> T findViewById(@IdRes int id) {
       if (id == NO_ID) { 
           return null;  
        }
       return findViewTraversal(id);
     }
    
    

    常见的泛型方法的声明方式:

    public <T extends View> T get(T t);
    public <T extends View> void get(T t);
    public <T,E> void get(T t,E e);
    

    <>里面是对参数t的约束和对类型T的声明,例如<T extends View>声明了一种类型T,且T是View的子类,然后根据传入的参数做一些处理,这里T的意义是在于对参数T t的约束和声明,任何View的子类都可以作为参数传进来进行处理。
    例如:

    ImageView img = findViewById(R.id.img);
    

    解谜:findViewById()其实并不能根据一个ID返还给你一个对的类型,什么意思呢?假设下面这两行代码都能编译通过并且运行

    ImageView img = findViewById(R.id.img);
    Button button= findViewById(R.id.img);
    

    这两行代码在编译后会是这个样子的:

    ImageView img = (ImageView)findViewById(R.id.img);
    Button button= (Button)findViewById(R.id.img);
    

    上面的例子也就是说该方法不知道你要什么,只是使用了泛型(T) this进行了强制类型转换,告诉编译器在编译的时候该方法返回的是一个泛型类型,要进行类型转换,明显,强转为Button的时候程序在运行时会崩溃。

    泛型的类型推断

    在之前Android开发中,需要在声明并赋值的时候,两侧都加上泛型类型。比方说这样:

    Map<String,Integer> map = new HashMap<String,Integer>(); 
    

    而现在开发时

    Map<String,Integer> map = new HashMap<>();
    

    而这也就是类型推断带来的简便效果

    相关文章

      网友评论

          本文标题:深入理解Java中的泛型(四)泛型方法的创建以及类型推断

          本文链接:https://www.haomeiwen.com/subject/kawlbltx.html