I have written the following:
public class DataContainer<Data>{
public DataContainer(Class<Data> clazz, String method) throws NoSuchMethodException, SecurityException{
clazz.getMethod(method);
}
}
And so I create my objects this way:
new DataContainer<SomeClass>(SomeClass.class, "get");
But I wanted it to look more like:
public class DataContainer<Data>{
public DataContainer(String method) throws NoSuchMethodException, SecurityException{
Data.getMethod(method);
}
}
And a construct call should look like this:
new DataContainer<SomeClass>("get");
How can I avoid passing the Data
class when I construct A DataContainer
object? I know Data
can't be manipulated at runtime (new DataContainer<>("get");
-> what is Data then?) but I've heard there are solutions to work around, unfortunately it seems like I haven't the vocab yet to google it.
Also it's a simplified version of my problem, we assume method is valid, public and hasn't arguments.
It's not really possible in the way you want to use your code, due to type erasure.
However, some generic information is preserved at runtime, i.e. when it is accessible to reflection. One such situation would be generics on the class hierarchy, i.e. you could do something like this (which we do quite frequently):
//Note that I used T instead of Data to reduce confusion
//Data looks a lot like an actual class name
public abstract class DataContainer<T>{
public DataContainer(String method) throws NoSuchMethodException, SecurityException {
Class<?> actualClass = getActualTypeForT();
//use reflection to get the method from actualClass and call it
}
protected Class<?> getActualTypeForT() {
//get the generic boundary here, for details check http://www.artima.com/weblogs/viewpost.jsp?thread=208860
}
}
//A concrete subclass to provide the actual type of T for reflection, can be mostly empty
public class SomeClassContainer extends DataContainer<SomeClass> {
//constructor etc.
}
Something similar should be possible for class fields or parameters, although I didn't test that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments