How to cast generic List types in java?

后端 未结 9 1006
离开以前
离开以前 2020-12-09 17:33

Well, I have a class Customer (no base class).

I need to cast from LinkedList to List. Is there any clean way to do this?

Just so you know, I need to cast it

9条回答
  •  悲&欢浪女
    2020-12-09 18:30

    Here's my horrible solution for doing casting. I know, I know, I shouldn't be releasing something like this into the wild, but it has come in handy for casting any object to any type:

    public class UnsafeCastUtil {
    
        private UnsafeCastUtil(){ /* not instatiable */}
    
        /**
        * Warning! Using this method is a sin against the gods of programming!
        */
        @SuppressWarnings("unchecked")
        public static  T cast(Object o){
            return (T)o;
        }
    
    }
    

    Usage:

    Cat c = new Cat();
    Dog d = UnsafeCastUtil.cast(c);
    

    Now I'm going to pray to the gods of programming for my sins...

提交回复
热议问题