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.
If you “implement” anything, you NEED to have an interface defined. Either you import one that already exists, or you have to create it. Either way, if it’s a public class (abstract or not) or an interface, it MUST be defined in a separate file. Unlike C++, this is a java requirement.
If:
then your project must be comprised of at least:
Period. No ifs/ands/buts.
But if you absolutely must have only one file in your project, you’ll have to get a byte-code generator and build your class and interfaces dynamically at runtime.
The real question is: what are you trying to accomplish? If it’s a Singleton/Factory, others have answered that already. If it’s to reduce the number of compilation units, then you’re out of luck. Java enforces the requirement that you have to do it this way.
EDIT AFTER AUTHOR UPDATES:
Java lets you do things like so:
Foo.java:
Which would accomplish what you want to achieve.