Alex Rivera | Logout

Spring getBean with type validation

Asked 2011-03-10T21:27:42.480
11

I'm using the method ApplicationContext.getBean(String name, Class requiredType). The bean is of type util:set. My code looks like:

Set<String> mySet = context.getBean("myBean", Set.class);

I want to know is how to do something like this to avoid the type casting warning:

Set<String> mySet = context.getBean("myBean", Set<String>.class);

I'm not sure if it's possible to define the type of a class in this way. Am I dreaming or is there a way to do this?

Thanks.

Edit
Report

1 Answer

1

maybe this can be usefull to you:

Set<String> setBean= null;
Map<String, Set> beans = applicationContext.getBeansOfType(Set.class);
for (Map.Entry<String, Set> bean: beans.entrySet()) {
    ParameterizedType thisType = (ParameterizedType) bean.getClass().getGenericSuperclass();
    Class<?> parametrizedClass= thisType.getActualTypeArguments()[0];
    if (parametrizedClass.isAssignableFrom(String)) {
        setBean= (Set<String>) bean;
    }
}

http://javahelp.redsaltillo.net

answered 2012-07-19T11:59:47.330

Your Answer