Why can't we switch on classes in Java 7+?

前端 未结 5 1914
故里飘歌
故里飘歌 2020-12-30 13:35

It seems to me that such a switch statement would make a lot of sense, but it gives a compile error :

public void m(Class c) {
   switch (c) {
       case S         


        
5条回答
  •  无人及你
    2020-12-30 14:03

    In Java 8 you can create your own "switch-case" using lambdas. Here's a simple example on how to switch on object class (not the Class object itself as you want, but this seems to be more useful):

    import java.util.function.Consumer;
    
    public class SwitchClass {
        private static final SwitchClass EMPTY = new SwitchClass(null) {
            @Override
            public  SwitchClass when(Class subClass,
                    Consumer consumer) { return this; }
    
            @Override
            public void orElse(Consumer consumer) { }
        };
    
        final T obj;
    
        private SwitchClass(T obj) {
            this.obj = obj;
        }
    
        @SuppressWarnings("unchecked")
        public  SwitchClass when(Class subClass,
                Consumer consumer) {
            if (subClass.isInstance(obj)) {
                consumer.accept((S) obj);
                return (SwitchClass) EMPTY;
            }
            return this;
        }
    
        public void orElse(Consumer consumer) {
            consumer.accept(obj);
        }
    
        public static  SwitchClass of(T t) {
            return new SwitchClass<>(t);
        }
    }
    
    
    

    Usage example:

    SwitchClass.of(obj)
        .when(Integer.class, i -> System.out.println("Integer: "+i.intValue()))
        .when(Double.class, d -> System.out.println("Double: "+d.doubleValue()))
        .when(Number.class, n -> System.out.println("Some number: "+n))
        .when(String.class, str -> System.out.println("String of length "+str.length()))
        .orElse(o -> System.out.println("Unknown object: "+o));
    

    If executes only the first matching branch, so for Double object only Double branch will be executed, not Number branch. The neat thing is that typecast is performed automatically.

    提交回复
    热议问题