Easy and safe cloning of methods, constructors, fields and parameters.
Kasper Nielsen
kasperni at gmail.com
Fri May 18 20:40:51 UTC 2018
Hi,
I'm making heavy use of class in java.lang.reflect such as methods,
constructors, fields and parameters in a library that I am trying to
secure. I both take them as parameters and return them from various
methods. Internally, I need to keep "safe" copies with the accessible bit
set. I do not want to expose these "safe" copies to the outside, but I want
to cache them for performance reasons.
However, I find it rather cumbersome to make safe copies of all of these.
Take, for example, a Constructor. If I want to return a copy
of a Constructor with the setAccessible set to false I need to do this:
Class<?> declaringClass = constructor.getDeclaringClass();
try {
return declaringClass.getConstructor(constructor.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new RuntimeException("This should never happen", e);
}
Copying a Method looks similar.
And if I want to make a safe copy of a parameter. I first need to clone its
declaring executable. And then run through all the parameters and see if
they are equal, because Parameter does not expose the index field.
Thoughts?
/Kasper
More information about the core-libs-dev
mailing list