简体   繁体   中英

Java constructor fails to work with varargs

I have the following enum which has a number of constructors:

public enum Route
{
   HOMEPAGE("", null, UserType.GUEST);

   Route(String baseName, String langFile, Entity entity) {}
   Route(String langFile, Entity entity)  {}
   Route(String langFile, UserType... availability) {}
   Route(String baseName, String langFile, UserType... availability) {}
}

In this case, I'm pretty clearly calling the 4th constructor when I define HOMEPAGE . But the problem is, I'm getting the error: Cannot resolve constructor Route(java.lang.String, null, com.foo.UserType) .

If I either remove the varags from the constructor, ie so it looks like:

   Route(String baseName, String langFile, UserType availability) {}

Or if I change the null when defining HOMEPAGE , ie:

   HOMEPAGE("", "", UserType.GUEST);

Then it works. But it doesn't make sense to me why that is. Why doesn't it detect that I'm calling the 4th constructor?

The problem is that null could be either a String or a UserType . So:

HOMEPAGE("", null, UserType.GUEST);

would match either the third or fourth constructor. Casting the null to a String would result in the fourth constructor being selected:

HOMEPAGE("", (String) null, UserType.GUEST);

It is correct that it does not know which constructor to pick, your call is:

Route(String, null, UserType)

This can surely not refer to the top two constructors.

It can however refer to Route(String, UserType) , as the null could be of type UserType .
It could also refer to Route(String, String, UserType) , as the null could be of type String .

There is your conflict.

Because null can either be a String or a UserType :

Route(java.lang.String, null, com.foo.UserType)

matches with both methodes :

Route(String langFile, UserType... availability) {}
Route(String baseName, String langFile, UserType... availability) {}

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