All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.sdk.json.ext.ClassWrapper Maven / Gradle / Ivy

There is a newer version: 1.5.17
Show newest version
package org.zodiac.sdk.json.ext;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Predicate;

public class ClassWrapper {

    private static Map, ClassWrapper> cached = new ConcurrentHashMap<>();

    public static ClassWrapper get(Class clz) {
        ClassWrapper cw = cached.get(clz);
        if (cw == null) {
            cw = new ClassWrapper(clz);
            ClassWrapper l = cached.putIfAbsent(clz, cw);
            if (l != null) {
                cw = l;
            }
        }
        return cw;
    }

    //clz //与函数同名,_开头
    private final Class _clz;
    //clz.all_fieldS
    private final Collection _fieldAllWraps;

    protected ClassWrapper(Class clz) {
        _clz = clz;

        Map map = new LinkedHashMap<>();
        scanAllFields(clz, map::containsKey, map::put);

        _fieldAllWraps = map.values();
    }

    public Class clz() {
        return _clz;
    }

    public Collection fieldAllWraps(){
        return _fieldAllWraps;
    }

    /*
     * 扫描一个类的所有字段
     */
    private static void scanAllFields(Class clz, Predicate checker, BiConsumer consumer) {
        if (clz == null) {
            return;
        }

        for (Field f : clz.getDeclaredFields()) {
            int mod = f.getModifiers();

            if (!Modifier.isTransient(mod) && !Modifier.isStatic(mod)) {
                f.setAccessible(true);

                if (checker.test(f.getName()) == false) {
                    consumer.accept(f.getName(), new FieldWrapper(clz, f));
                }
            }
        }

        Class sup = clz.getSuperclass();
        if (sup != Object.class) {
            scanAllFields(sup, checker, consumer);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy