java 对于<T>与<?>的用法区分

用具体的例子来说明

public class CglibProxyFactoryT<T> {

    /**
     * 得到目标对象
     */
    private Object target;
    
    public CglibProxyFactory() {
        
    }

    /**
     * 使用构造方法传递目标对象
     * @param target
     */
    public CglibProxyFactory(Object target) {
        super();
        this.target = target;
    }

    public Object invoke(String className, String methodName, Class<T> paramsType) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Object o = Class.forName(className).newInstance();
        Method method = o.getClass().getMethod(methodName, paramsType);
        Object dog123 = method.invoke(o, "dog123");
        return dog123;
    }
}
public class CglibProxyFactory {

    /**
     * 得到目标对象
     */
    private Object target;
    
    public CglibProxyFactory() {
        
    }

    /**
     * 使用构造方法传递目标对象
     * @param target
     */
    public CglibProxyFactory(Object target) {
        super();
        this.target = target;
    }

    public static Object invoke(String className, String methodName, Class<?> paramsType) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Object o = Class.forName(className).newInstance();
        Method method = o.getClass().getMethod(methodName, paramsType);
        Object dog123 = method.invoke(o, "dog123");
        return dog123;
    }
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        String s = "com.bngrp.FuterDemo.getString";
        String[] split = s.split("\\.");
        StringJoiner stringJoiner = new StringJoiner(".");
        for (int i = 0; i < split.length-1; i++) {
            stringJoiner.add(split[i]);
        }
        String className = stringJoiner.toString();
        String methodName = split[split.length-1];

        Object invoke = invoke(className, methodName, String.class);
        System.out.println(invoke);
        
        System.out.println("=======================上边是T的使用场景==下边是?的使用场景================================");
        
        CglibProxyFactoryT<String> factory = new CglibProxyFactoryT<String>();
        Object invoke1 = factory.invoke(className, methodName, String.class);
        System.out.println(invoke1);

 }

总结:从上边两个实例代码来看。T和?都表示了在编写时不确定的类型。

但是不同点在于。

  • T:如果一个类中的方法、参数使用了T来做泛型,那么类上边也必须要写T泛型。也就是说如果使用了T来做泛型,就必须在使用这个类的时刻,确定这个泛型的类型。
  • ?:如果想要使用?来做泛型。我们可以在写代码的时候,也不指定类型。也就是说,在使用类的时候不必确定这个泛型。
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值