VelocityTemplate中带有枚举参数的java Invoke方法
我正在使用apache velocity为我的应用程序生成配置文件,我遇到了使用enum参数调用方法的问题,如下所示:
我有一个CurrentcyUtil。java
package velocity;
public class CurrencyUtil {
public enum TestEnum {
A("Aaaa"), B("Bbbb");
private String value;
private TestEnum(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
public String test(TestEnum testEnum) {
return testEnum.getValue();
}
}
我举了个例子。java
package velocity;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import velocity.CurrencyUtil.TestEnum;
import java.io.*;
import java.util.Properties;
public class Example {
private String templateFile;
public Example(String templateFile) {
this.templateFile = templateFile;
}
public void run() {
StringReader reader = null;
try {
Velocity.init();
VelocityContext context = new VelocityContext();
CurrencyUtil cu = new CurrencyUtil();
context.put("cu", cu);
context.put("enumA", TestEnum.A);
Properties properties = new Properties();
properties.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
VelocityEngine engine = new VelocityEngine();
engine.init(properties);
// HELIO00022587
String data = readFile(templateFile);
if (data == null) {
return;
}
reader = new StringReader(data);
// HELIO00022587
StringWriter writer = new StringWriter();
boolean result = engine.evaluate(context, writer, "Test", reader);
if (result) {
writeToFile(writer.toString(), templateFile + ".result");
}
} catch (Exception e) {
System.out.println(e);
}
}
public String readFile(String filePath) throws IOException {
String data = null;
InputStream in = null;
try {
byte[] cbuf = new byte[8192];
int n;
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
in = new FileInputStream(filePath);
while ((n = in.read(cbuf)) >= 0) {
if (n > 0) {
out.write(cbuf);
}
count += n;
}
data = new String(out.toByteArray(), 0, count);
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
}
return data;
}
public void writeToFile(String data, String filePath) throws IOException {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.flush();
writer.close();
}
}
我有一个模板示例。vm
enumATest=$enumA
enumAValue=$cu.test($enumA)
#set( $enumB = "B")
enumBTest=$enumB
enumBValue=$cu.test($enumB)
输出为:
enumATest=A
enumAValue=Aaaa => Because enumA is putted to VelocityContext has TestEnum type, so 'test' method execute ok
#set( $enumB = "B")
enumBTest=B
enumBValue=$cu.test($enumB) => Variable enumB declare here, so understand as String => Throw NullPoiterException here
我的问题是:如何在模板文件中声明枚举变量 请帮帮我,非常感谢
共 (0) 个答案