Use interface or type for variable definition in java?

后端 未结 8 1941
挽巷
挽巷 2020-11-29 05:59
ArrayList aList = new ArrayList();

List aList = new ArrayList();

What\'s the difference between these two and which is better to use and why?

8条回答
  •  攒了一身酷
    2020-11-29 06:45

    I know of at least one case when declaring a variable with an interface does not work. When you want to use reflection.

    I made a bug fix on some code where I declared a variable as Map and assigned it an instance of HashMap. This variable was used as a parameter in a method call that was accessed via reflection. The problem is that reflection tried to find a method with HashMap signature and not the declared Map signature. Since there was no method with a HashMap as a parameter I was unable to find a method by reflection.

    Map map = new HashMap();
    
    public void test(Map m) {...};
    
    Method m = this.getClass().getMethod("test", new Class[]{map.getClass()});
    

    Will not find the method that uses the interface. If you make another version of test that uses HashMap instead then it will work - but now you are forced to declare your variable with a concrete class and not the more flexible interface...

提交回复
热议问题