java泛型

1.泛型方法

/*
 * <T>表示本方法持有一个不确定类型T,表示本方法是一个泛型方法
 * T 返回值类型为T类型的对象
 * Class<T> clazz:只有通过反射才能拿到泛型T的对象,因为方法运行时才知道泛型的真正类型
 * throws IllegalAccessException, InstantiationException:newInstance()方法抛出了异常
 * */

public class Demo {
    public <T> T method(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T t = clazz.newInstance();
        return t;
    }
}

 2.返回一个泛型类型

public <T> T evaluate(Class<T> clazz, String expression) throws IllegalAccessException, InstantiationException {
        return clazz.newInstance();
    }

    public <T> T executeDemoOne(Supplier<T> request){
        return request.get();
    }

    public <T> T executeDemo(Supplier<T> request) throws RejectedExecutionException {
        try {
            ExecutorService executor = Executors.newCachedThreadPool();
            Future<T> future = executor.submit(() -> request.get());
            T obj = future.get(1000l, TimeUnit.MILLISECONDS);
            return obj;
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

 

posted @ 2022-12-15 11:10  N神3  阅读(22)  评论(0编辑  收藏  举报