patternjavaMinor
Get object in a Set that is an instance of a generically specified type
Viewed 0 times
genericallytypeinstancegetthatobjectsetspecified
Problem
Are there ways to simplify the
Here is my code:
Test code:
getLoadComponent(Class 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 lc;
public T getLoadComponent(Class 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);
}
}Solution
As your current code now indirectly forces the set to only contain one of each component, then you could use a
Other comments:
Map instead. This would also reduce the need for the looppublic class Load {
Map, LoadComponent> lc;
public T getLoadComponent(Class type) {
return (T) lc.get(type);
}
}Other comments:
- Make sure the
Mapis set toprivate final
lcis not a good name. There's really no need to save bytes by shortening variable names. A better name would beloadComponents
- When adding items to the map, you can use
loadComponents.put(obj.getClass(), obj);
Code Snippets
public class Load {
Map<Class<? extends LoadComponent>, LoadComponent> lc;
public <T extends LoadComponent> T getLoadComponent(Class<T> type) {
return (T) lc.get(type);
}
}Context
StackExchange Code Review Q#61546, answer score: 4
Revisions (0)
No revisions yet.