How do I self-instantiate a Java class? I should not use any file other than its class file. Also assume that after the line where I initialized the NAME variable, they don't know the name of the class during compile-time.
Example:
public class Foo implements Bar {
public static final String NAME = "Foo";
private void instantiate() {
Bar baz = (Bar)Class.forName(NAME).newInstance();
}
//...
}
would be wrong since it needs to have another file called Bar.java
. It should be:
public class Foo {
/*
Instantiate self...
*/
}
I joined this programming challenges website where I am only allowed to submit one file per problem. I want to create a template class for all the classes that I'll be using for the challenges. So, what I have in mind is that I'll do this:
public class Foo {
public static final String NAME = "Foo";
public static void main (String[] args) throws IOException {
//Instantiate self and call launch(args)
Foo foo = new Foo();
foo.launch(args);
System.exit(0);
}
public void launch(String[] args) {
//...Do actual code here
}
}
I want to only change the class name and the NAME variable and not have to change the way I instantiate the class everytime I use the template class. With the current setup I have, I'll have to edit the line: Foo foo = new Foo();
and maybe the line below that.
You might also be wondering why I have to call launch()
and not do everything inside the main method. That's just something I got from my Java instructor. It's also since I can't use non-static methods inside the main()
method.