用static可以修饰方法,变量,还有代码块,这些被static修饰的,都是在类加载的时候就会执行,而不是创建对象的时候。代码块扩起来,可以用来做初始话的资源加载。
package com.sf;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static java.lang.System.out;
public class Test {
private static Map context = new HashMap<>();
private static final String resourceName = "/test.properties";
static {
InputStream in = null;
Properties prop = new Properties();
try {
in = Test.class.getResourceAsStream(resourceName);
prop.load(in);
context.put("name",(String)prop.get("name"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getContext(String pro){
return context.get(pro);
}
public static void main(String[] args) {
out.println(Test.getContext("name"));
}
}
像上面这个代码中,首先用static修饰这个方法getContext,Test类中的getContext可以作为对外的工具类,外面调用时可以直接使用,不需要创建实例。
然后static修饰的变量可以供static方法使用,这里的context可以作为一种缓存使用。
static修饰的代码块就是类加载的时候执行一次取加载配置文件中的内容
static导入包,可以省去写System,你可以在下面使用out.println 直接打印