這塊代碼是mock平臺中的一部分,由於mock的報文部分是通過freemarker模板返回的,而且模板名字的前綴和後綴都通過註解寫在類裏面了,下面中部分內容就是獲取數據模板文件的前綴和後綴的;
@SuppressWarnings({ "unchecked", "deprecation" })
private void init() {
Class<T> entityClass = null;
Class<?> c = getClass();
Type type = c.getGenericSuperclass();
if (type instanceof ParameterizedType) {
Type[] parameterizedType = ((ParameterizedType) type)
.getActualTypeArguments();
entityClass = (Class<T>) parameterizedType[0];
}
// 進行掃註解,確定模板的輸入輸出文件名
DataTemplate dataTemplate = entityClass
.getAnnotation(DataTemplate.class);
if (null != dataTemplate) {
this.outputName = dataTemplate.output();
if (NullOrEmpty.isNullOrEmpty(dataTemplate.template())) {
this.templateName = entityClass.getName();
} else {
this.templateName = dataTemplate.template();
}
} else {
this.outputName = entityClass.getName();
this.templateName = entityClass.getName();
}
this.freeMarkerCfg = new Configuration();
freeMarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
freeMarkerCfg.setDefaultEncoding(Charset.forName("UTF-8").name());
}
從類名可以看到主要是起初始化的作用,通過反射機制獲取對應類的類名,之後再通過註解獲取類裏面註解的具體內容來得到數據模板的前綴合後綴,剛看到這個不太明白,不過通過下面的代碼大致能看到這個類起的作用;
package com.neteae.web.test;
public class Person<T> {
}
package com.neteae.web.test;
import java.lang.reflect.*;
public class Student extends Person<Student>{
@SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
Student st=new Student();
@SuppressWarnings("rawtypes")
Class clazz=st.getClass();
//getSuperclass()獲得該類的父類
System.out.println(clazz.getSuperclass());
//getGenericSuperclass()獲得帶有泛型的父類
//Type是 Java 編程語言中所有類型的公共高級接口。它們包括原始類型、參數化類型、數組類型、類型變量和基本類型。
Type type=clazz.getGenericSuperclass();
System.out.println(type);
//ParameterizedType參數化類型,即泛型
ParameterizedType p=(ParameterizedType)type;
//getActualTypeArguments獲取參數化類型的數組,泛型可能有多個
Class<T> c=(Class<T>) p.getActualTypeArguments()[0];
System.out.println(c.getName());
System.out.println(c);
}
}
執行結果:
class com.neteae.web.test.Person
com.neteae.web.test.Person<com.neteae.web.test.Student>
com.neteae.web.test.Student
class com.neteae.web.test.Student
在利用spring MVC框架進行web開發的過程中,註解用的特別多,而這裏面反射機制起到了很大的作用,後續會繼續對這兩塊內容進行分析;