泛型方法

dao类:

package com.atguigu.javase.lesson8;

/**
 * 泛型类的声明
 * 在类中凡是可以使用类型的地方都可以使用类中声明的泛型
 */
public class Dao<T> {
    public T get(int id){
        T result = null;
        return result;
    }
    //在泛型类中使用类声明的泛型
    public void save(T entity){

    }

    /**
     * 在类(不一定是泛型类)中使用泛型方法。
     * 在方法的返回值前面使用<>声明泛型类型,则在方法的返回值,参数,返回体中都可以使用该类型
     */
    public <E> E getProperty(int i){
        return null;
    }
}

GenericMethodTest类:

package test.com.atguigu.javase.lesson8; 

import com.atguigu.javase.lesson8.Dao;
import com.atguigu.javase.lesson8.Person;
import org.junit.Test;

public class GenericMethodTestTest { 

    @Test
    public void testGenericMethod(){
        Dao<Person> dao = new Dao<>();
        Person person = dao.get(1);
        String name = person.getName();

        String name2 = dao.getProperty(2);
        int age = dao.getProperty(2);
    }
} 

猜你喜欢

转载自blog.csdn.net/ada_yangyang/article/details/80948288
今日推荐