开发者

How can I dynamically create a new instance of an object in Java?

I have a class called GetInput.java and I have a class called GetNotReleasedInput.java. I extend GetInput in GetNotReleasedInput. In GetInput, I call a private function called addLineToArray() and in that function I define a new class which contains details about the import.

However since I'm creating a generic class(GetInput) for all input files, I cannot say in addLineToArray():

AAData nextData = new AADat开发者_开发百科a();

because I have AA / Not Released, and in this case it should be NotReleased. So how can I dynamically make that new nextData in that function?


Either you make a protected method for creating the nextData object so that subclasses can decide how to do the manufacturing, or you have some kind of factory object (configurable at outer object creation time) that you delegate that to. The simplest way of doing the latter is to pass in a Class and call its newInstance() method, but there's a lot more complexity possible; a book on software patterns will go into quite a lot of depth on this.

But if you can just delegate the whole thing to the subclass of GetInput then that is easiest. (You don't provide enough information for me to be able to work out which pattern you should actually use.)


It sounds like you might want a virtual factory method into which you can place your object creation. In addLineToArray(), you then call your virtual createLineObject() instead of new AAData().

However, exactly what way to go depends on a number of factors: does the kind of data created depend on the GetInput class, or is that a separate decision (your GetInput classes may vary on behaviour, whereas the data may vary by format)? Are all data related (e.g. inherits from AAData)?

You should add more details on what you are trying to accomplish.


Java doesn't allow to modify metadata at runtime by default. You can write your own classloader with a asm and modify the bytecode at class loading time but that's probably not what you will want.

Instead, I suggest that all your classes data classes implement Iterable or something like that so you can easily join then and iterate over all lines without knowing the actual type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜