Normally a command-line Java application will have an entry method that looks something like:
public static void main(String... args) { /* Code that launches the application/deals with command line params here */ }
This is far too easy, there must be a way to NIH it ¬_¬. There are a few annoyances with the public static void main method.
- Args are passed in as an Array, rather than something like a List<String>
- We can’t choose to call the main method something other than main.
- It’s a bit obscure how the startup process works.
There is a common way to execute code on app startup without using a static void main method. You can use a static initialization block:
static { /* Code here run on class load. */ }
So we could launch our application from within a static initialization block. However this presents a number of problems:
- We get a nasty error when the application finishes (Exception in thread “main” java.lang.NoSuchMethodError: main)
- We have no access to the command line arguments
- We can’t have multiple “Main” classes with this method (Both static initialization blocks will be run, if both classes are loaded)
- It doesn’t really provide any benefits over static void main.
These problems can, however, all be overcome.
Suppressing NoSuchMethodError
We can just call System.err.close(); at the end of our initialization method.
Access to the command line arguments
This one is probably the most difficult. I’ve not found any “good” way to do this, but there is a hack that works at present on Sun’s Java, though it may stop working at any point.
sun.misc.VMSupport.getAgentProperties().get("sun.java.command")
This will give the command line string used to start the application. There are alternatives involving attaching to the currently running VM with the Agent API or shelling out to external processes and using platform-specific commands to work out the command used to start the application. If anyone knows a proper way to access the command line arguments using the public API then please let me know.
Multiple Main Classes
We need to get our initialization system to ignore invocations from classes other than the one used to start our application. This can be done by checking the length of the StackTrace. e.g.
new Throwable().fillInStackTrace().getStackTrace().length == 2;
Reflection Examples
With these 3 issues solved it’s possible to do things like:
package MainlessDemo; import java.util.List; import static uk.co.benjiweber.realjava.mainless.Bootstrap.init; public class ReflectionMainless { static { init(); } public void main(final List<String> args) { System.out.println("Hello World"); System.err.println("From std err"); for (String arg : args) { System.out.println(arg); } } } /* Output: $ javac -cp .:./RealJava.jar ./MainlessDemo/*.java && java -cp .:./RealJava.jar MainlessDemo.ReflectionMainless Foo Bar Baz Hello World From std err Foo Bar Baz */
Here a statically imported “init” method instantiates our main class, invokes our non-static main method, and passes it the command line arguments. The class to instantiate can be determined by walking back up the stack trace again.
We can also inject constructor arguments if we wish:
package MainlessDemo; import java.util.List; import static uk.co.benjiweber.realjava.mainless.Bootstrap.init; public class ReflectionMainlessWithArgs { // This time we pass in the constructor argument static { init("Hello World"); } private final String message; // Even though we load another class that is Launchable it doesn't get launched. static final ReflectionMainless test = new ReflectionMainless(); public ReflectionMainlessWithArgs(final String message) { this.message = message; } public void main(final List<String> args) { System.out.println(message + " (Passed in through constructor)"); for (String arg : args) { System.out.println(arg); } } } /* Output: $ javac -cp .:./RealJava.jar ./MainlessDemo/*.java && java -cp .:./RealJava.jar MainlessDemo.ReflectionMainlessWithArgs Foo Bar Baz Hello World (Passed in through constructor) Foo Bar Baz */
Interface Examples
Unfortunately, apart from substituting an argument Array for a List, we ‘ve not really improved anything. However, now that we’re in control of the initialization process we can do more interesting things, like use an interface:
public interface Launchable { public void main(List<String> args); }
package MainlessDemo; import java.util.List; import uk.co.benjiweber.realjava.mainless.Launchable; import static uk.co.benjiweber.realjava.mainless.Bootstrap.init; public class SaferMainless implements Launchable { static { init(new SaferMainless()); } public void main(final List<String> args) { System.out.println("Hello from a Launchable"); for (String arg : args) { System.out.println(arg); } } } /* Output: $ javac -cp .:./RealJava.jar ./MainlessDemo/*.java && java -cp .:./RealJava.jar MainlessDemo.SaferMainless Foo Bar Baz Hello from a Launchable Foo Bar Baz */
Now it’s clearer how the initialization process works, you can use your IDE to follow execution through from the init block to the main method. This also gives us the freedom to call our main method something different, and inject dependencies before reaching the main method.
package MainlessDemo; import java.util.List; import uk.co.benjiweber.realjava.mainless.Launchable; import static uk.co.benjiweber.realjava.mainless.Bootstrap.init; public class SaferAnonymousMainless { static { init(new Launchable() { public void main(final List<String> args) { SaferAnonymousMainless mainless = new SaferAnonymousMainless(); mainless.setMessage("I was injected manually"); mainless.someMethodNotCalledMain(args); } }); } private String message; public void setMessage(final String message) { this.message = message; } public void someMethodNotCalledMain(final List<String> args) { System.out.println(message); for (String arg : args) { System.out.println(arg); } } } /* Output: $ javac -cp .:./RealJava.jar ./MainlessDemo/*.java && java -cp .:./RealJava.jar MainlessDemo.SaferAnonymousMainless Foo Bar Baz I was injected manually Foo Bar Baz */
Source for the BootStrap.init method is here
Thanks to Faux for some of the ideas.
Yes I know this isn’t remotely a good idea, no need to tell me
7 Comments
buy Wedding Photographer Philippines Pinoy Photographer Wedding Pictures reviews
order Best Manila Photographers For Hire Prenuptial Packages Cheapest testimonials
cheap Fashion Photography Manila Philippines Commercial Photographers Services Cheap reviews
best Wedding Photos Photo Wedding Photography Portrait Photography Studios discounts
cheap Best Commercial Photographers Manila Wedding Photographers Events reviews
buy Manila Birthday Photographers Special Events For Baptismals Laguna discounts
order Best Commercial Photographers Manila Wedding Photographers Events reviews
buy Best Manila Photographers For Hire Prenuptial Packages Cheapest discounts
best Cheapest Photographers For Hire Photographers In Manila Affordable Wedding testimonials
best Bridal Photography Portrait Photography Studios Professional Photography reviews
buy Order Kava Tea Side Effects Reviews of Kava Herbal Tea Kava Tea Bags reviews
order Strongest Kava Tea Where To Buy Where To Buy Kava Kava Tea Website testimonials
order Where Can I Buy Kava Tea Online Buy Kava Kava Tea Cheapest Kava discounts
cheap Thai Kratom Effects Best Quality Kratom Resins Strongest Kratom Available reviews
order What Is The Best Kratom Experiences Kratom For Sale Buy Kratom Online discounts
order Brand New A900 Sony Online Sellers Sony A900 For Sale Sony A900 Sale discounts
buy Best Place To Buy Kratom Best MAENG da Kratom Online source sell discounts
buy Used Sony A900 For Sale Cheapest Sony A900 Sony A900 Refurbished testimonials
cheap Purchase Kava Kava Tea Kava Stress Relief Tea Kava Kava Tea Effects discounts
cheap Amazon Sony Alpha A900 Body Sony A900 Body A900 Vs D700 A900 Warranty discounts
cheap Purchase Indo Kratom Leaves For Sale Bali Premium Kratom Buy Online reviews
order Used Sony A900 For Sale Best Sony A900 Used Sony Dslr A900 Review testimonials
order Bleach For Toenail Fungus Over The Counter Toenail Fungus Treatment reviews
cheap Where To Buy Sony Alpha A900 Dslr Cheapest Sony A900 Review Body testimonials
buy How To Rid Toenail Fungus Get Rid Of Toenail Fungus OTC Creams testimonials
order Effective Home Cure For Toenail Fungus Getting Rid Of Toenail Fungus discounts
order How To Heal Toenail Fungus Toenail Removal Toenail Removal Fungus testimonials
cheap Best Cure For Toenail Fungus How To Kill Toenail Fungus remedies discounts
cheap Cost Of Laser Toenail Fungus Treatment Get Rid Of Toenail Fungus Fast testimonials
order What To Use For Toenail Fungus Treatment Over The Counter Product testimonials
buy Best Toenail Fungus Cure Toenail Fungus Home Treatment Best Cure testimonials
buy purchase Where Can I Buy Kratom blog Where To Buy Kratom product discounts
best purchase Ethnobotanicals sale Kratom Purchase discounts testimonials
cheap order Get Kratom website Where Can You Buy Kratom feedback reviews
best purchase Buy Kratom affordable Kratom Buy coupons reviews
best Wedding Photographer Philippines Pinoy Photographer Wedding Pictures discounts
best Best Manila Photographers For Hire Prenuptial Packages Cheapest testimonials
best purchase Where Can I Buy Kratom blog Where To Buy Kratom product discounts
buy purchase Buy Kratom affordable Kratom Buy coupons reviews
cheap purchase Ethnobotanicals sale Kratom Purchase discounts reviews
order order Get Kratom website Where Can You Buy Kratom feedback testimonials
best purchase Where Can I Buy Kratom blog Where To Buy Kratom product testimonials
buy order Get Kratom website Where Can You Buy Kratom feedback reviews
order Best Toenail Fungus Cure Toenail Fungus Home Treatment Best Cure reviews
order How To Rid Toenail Fungus Get Rid Of Toenail Fungus OTC Creams reviews
cheap Best Cure For Toenail Fungus How To Kill Toenail Fungus remedies testimonials
best Used Sony A900 For Sale Cheapest Sony A900 Sony A900 Refurbished discounts
buy Best Place To Buy Kratom Best MAENG da Kratom Online source sell testimonials
best Where Can I Buy Kava Tea Online Buy Kava Kava Tea Cheapest Kava testimonials
cheap Best Manila Photographers For Hire Prenuptial Packages Cheapest discounts
order Best Manila Photographers For Hire Prenuptial Packages Cheapest discounts
buy purchase Ethnobotanicals sale Kratom Purchase discounts discounts
best purchase Where Can I Buy Kratom blog Where To Buy Kratom product discounts
cheap purchase Buy Kratom affordable Kratom Buy coupons reviews
order order Get Kratom website Where Can You Buy Kratom feedback testimonials
buy order Get Kratom website Where Can You Buy Kratom feedback reviews
order How To Rid Toenail Fungus Get Rid Of Toenail Fungus OTC Creams discounts
best Best Toenail Fungus Cure Toenail Fungus Home Treatment Best Cure reviews
cheap What To Use For Toenail Fungus Treatment Over The Counter Product discounts
order Bleach For Toenail Fungus Over The Counter Toenail Fungus Treatment reviews
best Brand New A900 Sony Online Sellers Sony A900 For Sale Sony A900 Sale discounts
cheap Best Cure For Toenail Fungus How To Kill Toenail Fungus remedies testimonials
cheap How To Heal Toenail Fungus Toenail Removal Toenail Removal Fungus reviews
order Effective Home Cure For Toenail Fungus Getting Rid Of Toenail Fungus reviews
order Amazon Sony Alpha A900 Body Sony A900 Body A900 Vs D700 A900 Warranty discounts
buy Where Can I Buy Kava Tea Online Buy Kava Kava Tea Cheapest Kava reviews
best Purchase Indo Kratom Leaves For Sale Bali Premium Kratom Buy Online reviews
best Used Sony A900 For Sale Best Sony A900 Used Sony Dslr A900 Review reviews
cheap Thai Kratom Effects Best Quality Kratom Resins Strongest Kratom Available discounts
best Strongest Kava Tea Where To Buy Where To Buy Kava Kava Tea Website discounts
order Order Kava Tea Side Effects Reviews of Kava Herbal Tea Kava Tea Bags reviews
order Where To Buy Sony Alpha A900 Dslr Cheapest Sony A900 Review Body discounts
buy Used Sony A900 For Sale Cheapest Sony A900 Sony A900 Refurbished testimonials
cheap What Is The Best Kratom Experiences Kratom For Sale Buy Kratom Online discounts
cheap Best Place To Buy Kratom Best MAENG da Kratom Online source sell testimonials
order Best Commercial Photographers Manila Wedding Photographers Events discounts
cheap Manila Birthday Photographers Special Events For Baptismals Laguna testimonials
cheap Best Manila Photographers For Hire Prenuptial Packages Cheapest reviews
buy Bridal Photography Portrait Photography Studios Professional Photography testimonials
best Wedding Photographer Philippines Pinoy Photographer Wedding Pictures testimonials
cheap Best Manila Photographers For Hire Prenuptial Packages Cheapest reviews
best Cheapest Photographers For Hire Photographers In Manila Affordable Wedding testimonials
buy Wedding Photos Photo Wedding Photography Portrait Photography Studios discounts
cheap Best Commercial Photographers Manila Wedding Photographers Events reviews
By us at the moment to
grasp more knowledge and facts
at all events By us
contemporary to obtain more
low-down and facts regarding
odzywki
Nice to read your blog
Drop in on us now to buy more facts and facts in the matter of Visit us at times to buy more facts and facts anyway Kalendarze
naložba v srebro avtomobili
Buy Kratom New Jersey The Kratom Forest Kratom Hydrocodone
Kratom Ordering Smoking Kratom Leaves Better Than Kratom
Salvia Legal Kratom Review Buy Salvia Divinorum Plants
Kratom Extract Tea Kratom Buy Kratom Hydrocodone
Kratom Preparation Powder Kratom Info Swicki Kratom New York
If you wanna get high just visit http://drugreviews.info/
order bali kratom plants reviews
best dermology hair remover discounts
buy maqui berries testimonials
cheap canon canon mark ii discounts
order thai kratom dried discounts
cheap hair remover product discounts
cheap instant eye lift discounts
buy thai kratom resin reviews
cheap canon canon mark ii testimonials
buy dermology hair remover discounts
best phentermine 375 reviews
order canon 600d reviews
buy thai kratom resin discounts
cheap how to get pregnant reviews
cheap how to get pregnant testimonials
best intivar vaginal rejuvenation cream testimonials
best dermology hair remover reviews
cheap eye lift discounts
cheap thai kratom dried discounts
best provailen rheumatoid treatment testimonials
cheap canon kiss x5 testimonials
best maqui berries testimonials
buy thai kratom leaves reviews
buy intivar vaginal rejuvenation cream reviews
cheap sony alpha 77 testimonials
cheap hair remover product discounts
best canon canon mark ii reviews
buy canon t31 discounts
cheap canon 5d mk2 reviews
buy maeng da kratom leaves testimonials
best maqui berries reviews
buy canon 5d mark 2 reviews
buy maqui berry testimonials
buy bali kratom leaves reviews
buy canon 5d mk2 testimonials
buy maqui berry reviews
best canon kiss x5 discounts
buy dermology hair remover reviews
buy thai kratom plants discounts
cheap canon 600d reviews
best thai kratom resin testimonials
buy canon 600d reviews
cheap provailen rheumatism treatment testimonials
buy phen 375 discounts
order bali kratom plants discounts
order canon mark 2 reviews
cheap eyelift testimonials
cheap how to get pregnant guide discounts
order provailen rheumatism treatment testimonials
buy sony a77 discounts
Get up to 100000 forum backlinks with our backlinks service & massive targeted traffic Get great online web traffic using best backlink service today. We are able post your custom post up to 100’000 forums worldwide, get insane amount of backlinks and incredible targeted web traffic in very short time. Most affordable and most powerful service for web traffic and backlinks in the world!!!! Your post will be published up to 100000 forums worldwide your website or blog will get instant traffic and massive increase in seo rankings just after few days or weeks so your site will get targeted long term traffic from search engines. Order now: backlinks