Checking Java Collection Generic Type for an Empty Collection

前端 未结 4 1639
情话喂你
情话喂你 2021-01-15 05:56

I want to implement the following function:

public boolean checkType(Vector vec)
{
  // return true if its Vector and false otherwise         


        
4条回答
  •  野的像风
    2021-01-15 06:52

    Because of type erasure, this is not possible.

    Even if the vector is not empty, the collections library gives no real protection against putting things of different types in:

        Vector v = new Vector();
        v.add("foo");
        System.out.println(v.get(0));
    

    will run without error and nicely print the string value that shouldn't have been allowed.

    Thus any attempt to determine the generic type at run-time, even by checking the type of the first element, is not reliable.

    What you can do in your own generic code is to add a constructor argument and a field holding the value, so that your code does know the type at runtime.

    This tactic would be difficult to apply to the entire collections library, but a start at it for Vector would be:

    public class TypedVector extends Vector {
    
        private Class genericClass;
    
        public TypedVector(Class clazz) {
            super();
            this.genericClass = clazz;
        }
    
        // many other constructors ... but probably not all of them
    
        public Class getGenericClass() {
            return genericClass;
        }
    
        @Override
        public boolean add(E e) {
            if (!(genericClass.isAssignableFrom(e.getClass())))
                    throw new IllegalArgumentException("Incorrect class");
            return super.add(e);
        }
    
        // many other overrides for run-time type safety
    }
    

提交回复
热议问题