1. 加载所有 jar 包中同名的配置文件
/**
* 加载所有 jar 包中同名的配置文件
* @param resourceName
* @param classLoader
* @return
* @throws IOException
*/
public static Properties loadAllProperties(String resourceName,
ClassLoader classLoader) throws IOException {
Properties properties = new Properties();
Enumeration<URL> urls = classLoader.getResources(resourceName);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
InputStream is = null;
try {
URLConnection con = url.openConnection();
con.setUseCaches(false);
is = con.getInputStream();
properties.load(is);
} finally {
if (is != null) {
is.close();
}
}
}// end while
return properties;
}// end method loadAllProperties().
2. 通过反射读写对象的属性值
/**
* 设置对象实例的一个属性值
* @param obj
* @param fieldName
* @param value
*/
public static void setFieldValue(Object obj,String fieldName,Object value){
try {
Field field = obj.getClass().getDeclaredField(fieldName);
// step1 set public field
if((field.getModifiers() & Modifier.PUBLIC) != 0){
field.set(obj, value);
return;
}
// step2 invoke public setMethod
String setMethod = "set"
+ Character.toUpperCase(fieldName.charAt(0))
+ fieldName.substring(1);
Method method = obj.getClass().getDeclaredMethod(setMethod, new Class[]{value.getClass()});
if((method.getModifiers() & Modifier.PUBLIC) != 0){
method.invoke(obj, value);
return;
}
// step3 directly set value
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
} catch (NoSuchFieldException e) {
} catch(NoSuchMethodException e){
} catch(Exception e){
}
}
/**
* 返回对象实例的一个属性值
* @param obj
* @param fieldName
* @return
*/
public static Object getFieldValue(Object obj,String fieldName){
Object value = null;
try {
Field field = obj.getClass().getDeclaredField(fieldName);
// step1 get public field
if((field.getModifiers() & Modifier.PUBLIC) != 0){
return field.get(obj);
}
// step2 invoke public getMethod
String getMethod = "get"
+ Character.toUpperCase(fieldName.charAt(0))
+ fieldName.substring(1);
Method method = obj.getClass().getDeclaredMethod(getMethod, new Class[]{});
if((method.getModifiers() & Modifier.PUBLIC) != 0){
return method.invoke(obj);
}
// step3 directly get value
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
} catch (NoSuchFieldException e) {
} catch(NoSuchMethodException e){
} catch(Exception e){
}
return value;
}
3. 字符串前缀填充
/**
* 字符串前缀填充
* @param max 最大长度
* @param ch 填充字符
* @param value 原始值
* @return
*/
public static String fillPrefix(int max, char ch, String value){
if (value == null || value.length() >= max){
return value;
}
StringBuilder sb = new StringBuilder(value);
for (int i=value.length(); i<max; i++){
sb.insert(0, ch);
}
return sb.toString();
}
4. 首选项读写 [数据持久化到操作系统中]
import java.util.prefs.*;
public class Main{
public static void main(String[] args){
Preferences prefs = Preferences.userNodeForPackage(Main.class);
int freeTimes = prefs.getInt("freeTimes", 10);
freeTimes--;
prefs.putInt("freeTimes", freeTimes);
if (freeTimes < 0){
System.out.println("已过期,不可运行.");
System.exit(0);
}
System.out.println("还可运行 [" + freeTimes + "] 次.");
}
}
5. 动态编译 Java 源文件
package org.demo.compiler;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
/**
* 动态编译
* 参考: http://www.infoq.com/cn/articles/cf-java-byte-code
* @author
* @date 2010-12-26
* @file org.demo.compiler.DynamicCompiler.java
*/
public class DynamicCompiler {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(calculate("(3+4)*7 - 10"));
}
/**
* 计算表达式的值
* @param expression
* @return
*/
private static double calculate(String expression){
// class info
String className = "CalculatorMain";
String methodName = "calculate";
String source = "public class " + className + "{"
+ " public static double " + methodName + "(){"
+ " return " + expression + ";"
+ " }"
+ "}";
// compilation units
StringJavaFileObject obj = new StringJavaFileObject(className, source);
Iterable<? extends JavaFileObject> fileObjs = Arrays.asList(obj);
// compiler options
String path = DynamicCompiler.class.getClassLoader()
.getResource("").getPath();
if (path.startsWith("/")){
path = path.substring(1);
}
List<String> options = new ArrayList<String>();
options.add("-d");
options.add(path);
// compile the dynamic class
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
CompilationTask task = compiler.getTask(null, fileMgr, null, options, null, fileObjs);
boolean result = task.call();
// invoke the method
if (result){
ClassLoader loader = DynamicCompiler.class.getClassLoader();
try {
Class<?> clazz = loader.loadClass(className);
Method method = clazz.getMethod(methodName, new Class[]{});
Object value = method.invoke(null, new Object[]{});
return (Double)value;
} catch (Exception e){
e.printStackTrace();
throw new RuntimeException("内部错误: " + e.getMessage());
}
} else {
throw new RuntimeException("错误的表达式: " + expression);
}
}
/**
* 基于 String 的 java 对象
* @author
*
*/
static class StringJavaFileObject extends SimpleJavaFileObject{
private String content = null;
protected StringJavaFileObject(String className, String content) {
super(
URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension),
Kind.SOURCE
);
this.content = content;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException {
return content;
}
}
}
6. 在 java 中执行 javascript
http://www.ibm.com/developerworks/cn/java/j-lo-jse66/index.html
package org.demo.javascript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* 在 java 中执行 javascript
* @author
* @date 2010-12-26
* @file org.demo.javascript.JsMain.java
*/
public class JsMain {
public static void main(String[] args) {
String js = "println('Hello world!');"
+ "function getDatetime(){"
+ " var date = new Date();"
+ " var year = date.getFullYear();"
+ " var month = date.getMonth() + 1;"
+ " var day = date.getDate();"
+ " var hour = date.getHours();"
+ " var minute = date.getMinutes();"
+ " var second = date.getSeconds();"
+ " if (month < 10){ month = '0' + month;}"
+ " if (day < 10){day = '0' + day;}"
+ " if (hour < 10){hour = '0' + hour;}"
+ " if (minute < 10){minute = '0' + minute;}"
+ " if (second < 10){second = '0' + second;}"
+ " return year + '-' + month + '-' + day + ' '"
+ " + hour + ':' + minute + ':' + second;"
+ "}";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
engine.eval(js);
if (engine instanceof Invocable){
Invocable invocable = (Invocable)engine;
Object result = invocable.invokeFunction("getDatetime");
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Aviator 一个基于 java 的表达式引擎
http://code.google.com/p/aviator/
7. END