seancfoley / IPAddress

Java library for handling IP addresses and subnets, both IPv4 and IPv6
https://seancfoley.github.io/IPAddress/
Apache License 2.0
469 stars 63 forks source link

Can `AddressValueException(String message)` be made public? #127

Closed ryancdotorg closed 2 months ago

ryancdotorg commented 5 months ago

I am subclassing IPv4Address and IPv6Address, and I would like to be able to throw a subclass of AddressValueException with a custom error message.

Can you please make AddressValueException(String message) so I can do this?

seancfoley commented 5 months ago

At first glance, this seems reasonable for the next release. I presume you are using version 5.x.x.

In the meantime, you can use this trick:

 throwAddressValueException("my string");

public static AddressValueException throwAddressValueException(String arg) throws AddressValueException {
    Class<AddressValueException> clazz = AddressValueException.class;
    try {
        Constructor<AddressValueException> constructor = clazz.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        AddressValueException instance = constructor.newInstance(arg);
        throw instance;
    } catch( NoSuchMethodException | SecurityException | InstantiationException | 
            IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new Error(e);
    }
}
Exception in thread "main" inet.ipaddr.AddressValueException: my string
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at issue127.Issue.throwAddressValueException(Issue.java:19)
    at issue127.Issue.main(Issue.java:11)
ryancdotorg commented 5 months ago

Yes, I'm using 5.5.0 - the block splitting and merging functionality is great.

Thanks for the reflection example to tide me over, that will work for now.

seancfoley commented 2 months ago

This has been addressed in version 5.5.1

ryancdotorg commented 2 months ago

Thank you!