Java - a generic Java class instantiation example
less than 1 minute read
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class CommandFactory {
public static < T extends Command < R >, R extends CommandResult > T createCommand ( Class < T > classObject , Object ... params ) {
try {
T newInstance = classObject . newInstance () ;
if ( newInstance . initialize ( params )) {
return newInstance ;
}
} catch ( Exception e ) {
}
assert false ;
return null ;
}
}
public class TestCommandResult extends CommandResult {
}
public class TestCommand extends Command < TestCommandResult > {
private int index ;
public TestCommand () {
}
public bool initialize ( int idx ) {
this . index = idx ;
}
}
TestCommand testCmd = CommandFactory .< TestCommand , TestCommandResult > createCommand ( TestCommand . class , 1 ) ;