Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java有用代码片段 #15

Open
TFdream opened this issue Sep 19, 2018 · 0 comments
Open

Java有用代码片段 #15

TFdream opened this issue Sep 19, 2018 · 0 comments

Comments

@TFdream
Copy link
Owner

TFdream commented Sep 19, 2018

json序列化

1.google gson

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

2.Gson对象序列化

private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

String jsonString = gson.toJson(obj);  

3.Gson对象反序列化

//1.parse object
Person person = gson.fromJson(jsonString, Person.class);  
//2.parse array
List<Person> list = gson.fromJson(jsonString, new TypeToken<List<Person>>(){}.getType());  

4.Gson JsonSerializer 与 JsonDeserializer

例如 针对Date 序列化与反序列化,如下:

import com.google.gson.*;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * @author Ricky Fung
 */
public class JsonUtils {
    private static final Gson GSON = new GsonBuilder()
            .registerTypeAdapter(Date.class, new JsonDateSerializer())
            .create();

    public static String toJson(Object obj) {
        return GSON.toJson(obj);
    }

    public static <T> T parseObject(String json, Class<T> classOfT) {
        return GSON.fromJson(json, classOfT);
    }
    public static <T> T parseObject(String json, Type typeOfT) {
        return GSON.fromJson(json, typeOfT);
    }
}

/**
 * gson Date序列化/反序列化
 * @author Ricky Fung
 */
class JsonDateSerializer implements
        JsonSerializer<Date>,JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json==null || json.isJsonNull()) {
            return null;
        }
        String dateStr = json.getAsString();
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        return DateUtils.parseDate(dateStr);
    }

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        if (src==null) {
            return null;
        }
        return new JsonPrimitive(DateUtils.format(src));
    }
}

Cache

1.google guava

Guava: Google Core Libraries for Java.

1.guava

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>

2.quick started

LoadingCache<K, V> caches = CacheBuilder.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build(new CacheLoader<K, V>() {
                    @Override
                    public V load(K key) throws Exception {
                        return generateValueByKey(key);
                    }
                });
try {
    caches.get(key);
} catch (ExecutionException e) {
    e.printStackTrace();
}

2. Caffeine

Caffeine is a high performance, near optimal caching library based on Java 8.

1.caffeine

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.6.2</version>
</dependency>

2.quick started

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .maximumSize(10_000)
    .expireAfterWrite(5, TimeUnit.MINUTES)
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(key -> createExpensiveGraph(key));

获取默认类加载器

摘自Spring框架中的 org.springframework.util.ClassUtils 中更合理的实现方式:

	public static ClassLoader getDefaultClassLoader() {
		ClassLoader cl = null;
		try {
			cl = Thread.currentThread().getContextClassLoader();
		}
		catch (Throwable ex) {
			// Cannot access thread context ClassLoader - falling back...
		}
		if (cl == null) {
			// No thread context class loader -> use class loader of this class.
			cl = ClassUtils.class.getClassLoader();
			if (cl == null) {
				// getClassLoader() returning null indicates the bootstrap ClassLoader
				try {
					cl = ClassLoader.getSystemClassLoader();
				}
				catch (Throwable ex) {
					// Cannot access system ClassLoader - oh well, maybe the caller can live with null...
				}
			}
		}
		return cl;
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant