Say I am using a Java library that has the following method
public static SomeInterface foo();
The interface SomeInterface
has multiple implementations, some of which are protected
within the library's package. One of these implementation is TheProtectedClass
What would be the best way to check if the object returned by foo()
is an instance of TheProtectedClass
?
My current plan is to create an Utils class that lives within my project but in the same package as the protected class. This Utils can refer to TheProtectedClass
since it is in the same package and thus it can check if an object is instanceof TheProtectedClass
.
Any other ideas?
EDIT: Some people are asking "why" so here is more context.
I am using jOOQ and in some part of my code, I want to know if the Field instance that I have is an instance of Lower.
Currently, I use field.getName().equals("lower")
but this isn't as robust as I'd like it to be.
I realize that since Lower
is a protected class, it isn't part of the API and that it can change but I am ok with that.
It appears that the best solution is to create a package in your project that has the same package as the package-private class and either expose TheProtectedClass.class
as a Class<?>
or simply add a simple method that checks if your Object
is instanceof TheProtectedClass
.
This does not require reflection, it is fast and relatively safe (compilation will break if the package-private class changes name).