Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constructor fails to work with varargs

Tags:

java

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, i.e so it looks like:

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

Or if I change the null when defining HOMEPAGE, i.e:

   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?

like image 802
Ali Avatar asked Dec 02 '25 01:12

Ali


1 Answers

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);
like image 182
hmjd Avatar answered Dec 03 '25 13:12

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!