tags:

views:

125

answers:

2

I have a Java method with the following signature:

public <T> List<HtmlOptionsComposite> convertToHtmlOptionsCompositeList
    (List<? extends T> objects, 
     Class<T> clazz, 
     String getValueMethodName, 
     String getDescriptionMethodName, 
     String getDiscontinuedMethodName)
{ ... }

The clazz parameter is required by the method to use reflection (clazz.getMethod(...)) on each of the given objects, but do I really need to pass it in as a parameter to the method? Is there any way I can refactor the code to work out what clazz should be automatically?

+3  A: 

You could call getClass() on the first object in the list. That would give you a Class<? extends T> rather than Class<T> though - and in particular that means may will be some methods which are given which shouldn't be (because they're not methods on T itself).

Jon Skeet
I tried that, but it return Class<? extends Object> instead of ? extends T :(
GaZ
Oh, Actually, duh. Since I already know that the list of objects extends T then I don't really need to declare my local variable as a Class<T>, so I can just use "Class clazz = objects.get(0).getClass()"Ta!
GaZ
+1  A: 

Consider:

public interface T {
    void foo (); 
}

class S {
    private class U implements T {
        public void foo () { ... }
    }

    private class V implements T {
        public void foo () { ... }
    }
}

If you use the class of the first instance of the list, then that may not be the same class as the class of the other instances of the list - the list may be a mix of S.U and S.V instances. So you would need to call getClass() on every instance in the list.

Also, although T.foo() is public, the implementations in U and V will not be accessible outside of S, as U and V are private classes.

So without the class parameter, then for each element you would need to get its class, look up the method by name and set that method accessible. That's possible, but it's a lot more work than getting a public method once.

Pete Kirkham