用具体的例子来说明
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来做泛型,就必须在使用这个类的时刻,确定这个泛型的类型。
- ?:如果想要使用?来做泛型。我们可以在写代码的时候,也不指定类型。也就是说,在使用类的时候不必确定这个泛型。
版权声明:本文为TNT_D原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。