Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Are there ways to simplify the getLoadComponent(Class<T> type) method? The call LoadComponentFX lcfx = l.getLoadComponent(LoadComponentFX.class); seams a bit clumsy to me.

Here is my code:

public abstract class LoadComponent {}

public class LoadComponentFX extends LoadComponent {}

public class Load {
    Set<LoadComponent> lc;

    public <T extends LoadComponent> T getLoadComponent(Class<T> type) {
        for (final LoadComponent l : lc) {
            if (type.isInstance(l)) {
                return (T) l;
        return null;

Test code:

public class LoadTest {
    public static void main(final String[] args) {
        Load l = new PointLoad();

        LoadComponentFX lcfx = l.getLoadComponent(LoadComponentFX.class);
share|improve this question
up vote 4 down vote accepted

As your current code now indirectly forces the set to only contain one of each component, then you could use a Map instead. This would also reduce the need for the loop

public class Load {
    Map<Class<? extends LoadComponent>, LoadComponent> lc;

    public <T extends LoadComponent> T getLoadComponent(Class<T> type) {
        return (T) lc.get(type);

Other comments:

  • Make sure the Map is set to private final
  • lc is not a good name. There's really no need to save bytes by shortening variable names. A better name would be loadComponents
  • When adding items to the map, you can use loadComponents.put(obj.getClass(), obj);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.