简体   繁体   中英

Different data types in java

I am using reflection to extract the field type from Java objects at runtime. These fields are being categorized as:

  • Primitive Type
  • Fields having package name starting with Java.lang.*
  • Fields having package name starting with Java.util.*
  • Array types

For Custom Objects(User defined) in the field: These are again explored for their fields and their respective fields categorized.(Recursive call)

I wanted to know whether the above categorization will be enough for any object or some extra categories are required for more meaningful categorization.

I do stuff like this for debugging and I just check for Iterable and sometimes Map . Trying to account for every possible type statically is a bit of a fool's errand. If you want to handle any possible type, a good idea is to just create a simple way to register a converter function. Then clients of the API can do essentially whatever they want.

Here's a relatively quick example:

package mcve.reflect;

import java.lang.reflect.*;
import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public interface DebugReadout {
    /**
     * Prints a readout of all instance fields in {@code this} to the
     * specified print stream.
     * 
     * @param   out 
     * @throws  NullPointerException
     */
    default void readout(PrintStream out) {
        Class<?> clazz = getClass();
        out.printf("%s {%n", clazz.getSimpleName());
        do {
            for (Field f : clazz.getDeclaredFields()) {
                if (!Modifier.isStatic(f.getModifiers())) {
                    String value;
                    try {
                        f.setAccessible(true);
                        value = Details.toString(f.get(this));
                    } catch (ReflectiveOperationException
                           | SecurityException x) {
                        value = "UNAVAILABLE";
                    }
                    out.printf("    %s = %s%n", f.getName(), value);
                }
            }
        } while((clazz = clazz.getSuperclass()) != Object.class);
        out.printf("}%n");
    }
    /**
     * Registers a converter function.
     * 
     * @param   <T>
     * @param   type
     * @param   fn 
     * @throws  NullPointerException
     */
    static <T> void put(Class<T> type, Function<? super T, String> fn) {
        Objects.requireNonNull(type);
        Objects.requireNonNull(fn);
        Details.CONVERTERS.put(type, fn);
    }
    /**
     * Returns a converter function or {@code null} if one didn't exist.
     * 
     * @param   <T>
     * @param   type
     * @return  a converter function
     */
    @SuppressWarnings("unchecked")
    static <T> Function<? super T, String> get(Class<T> type) {
        Objects.requireNonNull(type);
        synchronized (Details.CONVERTERS) {
            Function<?, String> fn = Details.CONVERTERS.get(type);
            if (fn == null) {
                for (Class<?> key : Details.CONVERTERS.keySet()) {
                    if (key.isAssignableFrom(type)) {
                        fn = Details.CONVERTERS.get(key);
                        break;
                    }
                }
            }
            return (Function<? super T, String>) fn;
        }
    }
}

class Details {
    static final Map<Class<?>, Function<?, String>> CONVERTERS =
        Collections.synchronizedMap(new HashMap<>());

    static <T> String toString(T obj) {
        if (obj == null) {
            return "null";
        }
        @SuppressWarnings("unchecked")
        Function<? super T, String> fn =
            (Function<? super T, String>)
                DebugReadout.get(obj.getClass());
        if (fn != null) {
            return fn.apply(obj);
        }
        if (obj.getClass().isArray()) {
            return IntStream.range(0, Array.getLength(obj))
                            .mapToObj(i -> toString(Array.get(obj, i)))
                            .collect(Collectors.joining(", ", "[", "]"));
        }
        if (obj instanceof Iterable<?>) {
            return StreamSupport.stream(((Iterable<?>) obj).spliterator(), false)
                                .map(e -> toString(e))
                                .collect(Collectors.joining(", ", "[", "]"));
        }
        if (obj instanceof Map<?, ?>) {
            return toString(((Map<?, ?>) obj).entrySet());
        }
        return obj.toString();
    }
}

A more robust routine would keep an IdentityHashMap of every object seen so far (perhaps excluding known value types like String and Integer ) so you don't end up with infinite recursion in a case where two objects reference each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM