2011. 4. 4.

[Java]Interface를 사용한 reflection 흉내내기

원본(Src) : http://stackoverflow.com/questions/1943021/equivalent-of-define-in-java


Depending on what you are doing (not quite enough information) you could do something like this:


interface Foo
{
void foo();
}

class FakeFoo
implements Foo
{
public void foo()
{
// do nothing
}
}

class RealFoo
{
public void foo()
{
// do something
}
}


and then provide a class to abstract the instantiation:


class FooFactory
{
public static Foo makeFoo()
{
final String name;
final FooClass fooClass;
final Foo foo;

name = System.getProperty("foo.class");
fooClass = Class.forName(name);
foo = (Foo)fooClass.newInstance();

return (foo);
}
}


Then run java with -Dfoo.name=RealFoo|FakeFoo

Ignored the exception handling in the makeFoo method and you can do it other ways... but the idea is the same.

That way you compile both versions of the Foo subclasses and let the developer choose at runtime which they wish to use.

댓글 없음:

댓글 쓰기

[다자녀할인] 2자녀 이상 모든 공항 주차장 50% 할인받기 (둘 중 한명은 15세 이하)

다자녀 기준이 2명으로 완화되면서 자녀가 2명만 되어도 공영주차장 50%(지역에 따라 30%인 곳 도 있음) 할인이 가능하고, 전국의 공항주차장도 50% 할인이 가능하다. "다둥이카드" 나 "경기 I Plus 카드"...