Java 常用套路(持续更新)

灌水文章,勿喷。实例中的代码有的直接来源于网上,已经忘了从哪里摘抄过来了。囧~~~~~~

访问私有变量

field.setAccessible(true);
BlockingQueue quue =  (BlockingQueue)field.get(emailManager);
EmailObj emailObj = quue.take();

反射修改类方法权限

Method method = DeployTask.class.getDeclaredMethod("getDeployHosts", SubTask.class);
method.setAccessible(true);
String deployHost = (String) method.invoke(deployTask, subTask);
Assert.assertEquals(deployHost, host + Constants.SPLIT_FLAG + "0");

Jackson 数据反射

反射为 HashMap 类型

TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap map = mapper.readValue(json, mapType);

同样的,我们应该可以使用 Jackson 提供相关类对例如 LinkedListSet 这些集合类型进行反射。具体请见 Deserializing into a HashMap of custom objects with jackson

读取classes目录下的文件

File file = new File(loader.getResource("admin.pub").getFile());

将 stacktrace 输出到日志文件

StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logger.error(trace.toString());

格式化时间

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()

读取InputStream里面的内容

使用Apache commons IOUtils类,下面这些方法的限制是指针对本地文件,对于TCP的input stream并不适用。

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

// 更加鸡贼的写法是
String theString = IOUtils.toString(inputStream, encoding);

// 对于Spring用户,可以使用如下的代码
import java.nio.charset.StandardCharsets;
import org.springframework.util.FileCopyUtils;

public String convertStreamToString(InputStream is) throws IOException { 
    return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
}

long to timesptamp

long time = System.currentMilliseconds();
new Timestamp(time);

发送Http请求

GET
public static String httpGet(String requestUrl, Map headers) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(requestUrl);

    for (String key: headers.keySet()) {
        get.setHeader(key, headers.get(key));
    }

    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();

    return EntityUtils.toString(resEntityGet);
}
POST
public static String postJson(String address, Map headers) {
    try {
        URL url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        return IOUtils.toString(connection.getInputStream(), "UTF-8");
    } catch (MalformedURLException e) {
        logger.error("address: " + address, e);
    } catch (IOException e) {
        logger.error("address: " + address, e);
    }
    
    return null;
}

log4j

限制 log4j debug 范围:

log4j.logger.com.datastory.ops.resource=DEBUG, DRFA, CONSOLE

数据结构

一行代码初始化 List
List places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
一行代码初始化 Map
ImmutableMap.of("cookie", RConfig.getInstance().get(RConstant.DEPLOY_TOKEN))

Gson

如何序列化/反序列化 abstract class

先创建一个 adapter 序列化 abstract class,在本例子中, adapter 里面调用了 Result 的 serialize 方法,将 Result 序列化。

import com.google.gson.*;

import java.lang.reflect.Type;

/**
 * Created by zhuohui on 17/6/26.
 */
public class ResultAdapter implements JsonSerializer, JsonDeserializer {
    public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();
        Result result = (Result) src;
        result.serialize(jsonObject);
        return jsonObject;
    }

    @Override
    public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject object = json.getAsJsonObject();
        String type = object.get("type").getAsString();
        Result output = ResultFactory.createResult(type);
        output.deserialize(object);
        return output;
    }
}

然后在创建 Gson 对象之前,注册 Result.class 的 adapter,注意使用 registerTypeHierarchyAdapter 方法,才能够对 Result.class 的所有子类生效

new GsonBuilder()
    .registerTypeHierarchyAdapter(Result.class, new ResultAdapter())
    .create()
    .toJson(report)
如何反序列话 List of objects
Type listType = new TypeToken>(){}.getType();
List histories = new Gson().fromJson(json, listType);

单例

静态内部类实现的单例:

public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE; 
    }  
}

你可能感兴趣的:(Java 常用套路(持续更新))