I want to create something I can only describe as a "code factory method".
To avoid code repetition, I want to create a method which contains the code to be executed, but with "placeholders" where the types are supposed to go. The method would of course take these types as parameters an开发者_开发知识库d place each one in its appropriate spot. For example:
void factory(placeholder1, placeholder2){
ArrayList<placeholder1> List = new ArrayList<placeholder1>;
Placeholder2 variable;
}
factory(String, Integer);
would yield:
ArrayList<String> List = new ArrayList<String>;
Integer variable;
any ideas how I would go about this?
Your help is much appreciated.
EDIT: Thank you for all the feedback. I was going with the generic approach and it was working for awhile until I came across what I believe someone mentioned earlier. I want to use one of the methods within one of the generic objects like:
Integer variable = new Integer();
variable.isInteger();It doesn't appear that I will be able to do this using generics. Is there possibly a workaround to this?
Rather than simply adopting generics, it looks like you want some sort of macro facility. Java doesn't have that. For example, to expand your example a bit, you couldn't do anything like this:
factory(String, Integer);
List.get(variable);
Here's how it would look:
<placeholder1, placeholder2> void factory(){
ArrayList<placeholder1> List = new ArrayList<placeholder1>;
placeholder2 variable;
}
this.<String, Integer> factory();
But I agree with matt that you should read up on generics. Also, be cautious of type-erasure as this might not do everything you expect.
精彩评论