简体   繁体   中英

switch case on class type java

I want to create a function that returns a value of the type passed as an argument. for that I wanted to use a switch on the type of the argument, but I didn't have to do the right thing. what is the correct way:

public <T> T threadLocalRandom(Class<T> type){
    switch (type){
        case Integer i:
            return (T) ThreadLocalRandom.current().nextInt();
        case Double:
            return ThreadLocalRandom.current().nextDouble();
        case Boolean:
            return ThreadLocalRandom.current().nextBoolean();
    }
}

public <T> T threadLocalRandom(Class<T> type){
    switch (type.getClass().getSimpleName()){
        case "Integer":
            return (T) ThreadLocalRandom.current().nextInt();
        case "Double":
            return ThreadLocalRandom.current().nextDouble();
        case "Boolean":
            return ThreadLocalRandom.current().nextBoolean();
    }
}

in any case I have an error because I return an Interger, a Double or a Boolean while the method wants to return a type T Thanks How to make the Type T match the type returned by the switch?

There is a dynamic cast() operation you can apply to the result:

return type.cast(ThreadLocalRandom.current().nextInt());

I'd be curious to know how you use your method. It seems likely there would be a cleaner way to embody and access this functionality.

As ugly as it is, you can promote each type to the corresponding wrapper and then cast to T . Something like,

public static <T> T threadLocalRandom(Class<? super T> type) {
    switch (type.getSimpleName().toLowerCase()) {
    case "integer":
        return (T) Integer.valueOf(ThreadLocalRandom.current().nextInt());
    case "double":
        return (T) Double.valueOf(ThreadLocalRandom.current().nextDouble());
    case "boolean":
        return (T) Boolean.valueOf(ThreadLocalRandom.current().nextBoolean());
    }
    return null;
}

I tested with

public static void main(String[] args) {
    System.out.println(threadLocalRandom(Integer.class));
    System.out.println(threadLocalRandom(Double.class));
    System.out.println(threadLocalRandom(Boolean.class));
}

And I got

1704391064
0.3620604124031841
false

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