灌水文章只搁,勿噴扫尖。實例中的代碼有的直接來源于網(wǎng)上斗躏,已經(jīng)忘了從哪里摘抄過來了层释。囧~~~~~~
訪問私有變量
field.setAccessible(true);
BlockingQueue<EmailObj> quue = (BlockingQueue<EmailObj>)field.get(emailManager);
EmailObj emailObj = quue.take();
反射修改類方法權(quán)限
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 數(shù)據(jù)反射
反射為 HashMap 類型
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);
同樣的截驮,我們應(yīng)該可以使用 Jackson 提供相關(guān)類對例如 LinkedList笑陈,Set 這些集合類型進行反射。具體請見 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里面的內(nèi)容
使用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);
發(fā)送Http請求
GET
public static String httpGet(String requestUrl, Map<String, String> 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<String, String> 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
數(shù)據(jù)結(jié)構(gòu)
一行代碼初始化 List
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
一行代碼初始化 Map
ImmutableMap.of("cookie", RConfig.getInstance().get(RConstant.DEPLOY_TOKEN))
Gson
如何序列化/反序列化 abstract class
先創(chuàng)建一個 adapter 序列化 abstract class蓬网,在本例子中, adapter 里面調(diào)用了 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;
}
}
然后在創(chuàng)建 Gson 對象之前,注冊 Result.class 的 adapter禽额,注意使用 registerTypeHierarchyAdapter 方法锯厢,才能夠?qū)?Result.class 的所有子類生效
new GsonBuilder()
.registerTypeHierarchyAdapter(Result.class, new ResultAdapter())
.create()
.toJson(report)
如何反序列話 List of objects
Type listType = new TypeToken<List<GraphHistory>>(){}.getType();
List<GraphHistory> histories = new Gson().fromJson(json, listType);
單例
靜態(tài)內(nèi)部類實現(xiàn)的單例:
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}