Skip to content

Instantly share code, notes, and snippets.

@3100
Last active December 14, 2015 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3100/5079902 to your computer and use it in GitHub Desktop.
Save 3100/5079902 to your computer and use it in GitHub Desktop.
a class reflection sample in Java.
public class DryRunner extends RunnerBase {
public DryRunner(String file) {
super(file);
}
public Boolean delete()
{
log("dry:delete.");
return true;
}
public Boolean doComplexThing(){
log("dry:complex");
return true;
}
}
public interface IRunner {
public Boolean delete();
public Boolean doComplexThing();
}
import java.lang.reflect.Constructor;
public class ReflectionSample {
public static void main(String[] args) {
run("huga", "DryRunner");
run("hoge", "WetRunner");
}
// 簡便のため、String fileに変更している。runnerNameにクラス名を指定。
public static void run(String file, String runnerName){
// 引数の型を定義
Class<? extends String> fileParam = String.class;
try{
Class<?> cls = Class.forName(runnerName);
Constructor ct = cls.getConstructor(fileParam);
RunnerBase runner = (RunnerBase)ct.newInstance(file);_
runner.delete();
runner.doComplexThing();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class RunnerBase implements IRunner {
protected String _file;
public RunnerBase(String file) {
_file = file;
}
public Boolean delete()
{
return false;
}
public Boolean doComplexThing(){
return false;
}
protected void log(String str){
System.out.println(str);
}
}
public class WetRunner extends RunnerBase {
public WetRunner(String file) {
super(file);
}
public Boolean delete()
{
log("wet:delete.");
return true;
}
public Boolean doComplexThing(){
log("wet:complex");
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment