Dynamically Casting class and calling appropriate methods - java

I am writing a utility which uses some classes defined in a 3rd party library which i do not control.
I would like the to know what would be a good way to handle situations like the one described below :
3rd party library has a base abstract class 'Food' which is extended by 'Appetizer','Entree',"Beverage' and 'Dessert'. (all part of 3rd Party Library)
I am writing a 'WaiterUtility' which has methods to serve each type of food.
I want to avoid an endless chain of instanceof checks .
`
Class WaiterUtility{
public serveItems(Food[] items)
{
for(Food aFood : items){
//how do i call the sub-class specific methods i wrote below?
}
}
private void serve(Appetizer aFood){//somecode}
private void serve(Entree aFood){//somecode}
private void serve(Beverage aFood){//somecode}
private void serve(Dessert aFood){//somecode}
}
`

If at all possible, I would implore you NOT to use reflection as TBotV63 does in his answer (he even says to avoid it). From the Oracle documentation:
If it is possible to perform an operation without using reflection, then it is preferable to avoid using it.
So, obviously we're inclined to say that all Foods can be served, and that any Waiter can serve any kind of Food. Ideally a good API would therefore expose methods that would be sufficient for a serve(Food) method to do the job without knowledge of what kind of food it is. It seems like your question implies that this is not the case, and therefore something more needs to be done.
If the 3rd party library accepts community input then you should try to open an issue or a pull request to add the functionality.
Obviously that's not always possible, so the next best thing to do would be to create an interface (something like Serveable) which defines the methods you would need, and then subclass the different types of food while implementing that interface. Then you would have Waiter.serve(Serveable).
This is more work than reflection or many uses of instanceof, but it is better OO design.
Why reflection is bad
The documentation for reflection points out 3 drawbacks of reflection
exposure of internals
performance
security
While you might not care about 2 or 3, 1 is especially bad.
... use of reflection can ... render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
Why instanceof is bad (in this case)
serveItems(Food[]) implies to the caller that if you pass it several Food items, it will serve each of them. However this is not really the case. We can only serve certain sub-classes of Food, and we will have run-time errors if we try anything else. Java is a nice typesafe language, we like compile-time errors much more than run-time errors.
Another downside is that additional code needs to be added to Waiter every time a new sub-class of Food is added or changed. This becomes a cross-cutting concern and makes the code unscalable from a development perspective.
These are by no means the only downsides/issues, just a couple examples.

You can try following code:
Class WaiterUtility{
private Map<Class<? extends Food>, Waiter> waiters = new HashMap<>();
WaiterUtility() {
waiters.put(Appetizer.class, new AppetizerWaiter());
waiters.put(Entree.class, new EntreeWaiter());
waiters.put(Beverage.class, new BeverageWaiter());
waiters.put(Dessert.class, new DessertWaiter());
}
public serveItems(Food[] items)
{
for(Food aFood : items){
waiter.get(aFood.getClass()).serve(aFood);
}
}
private static abstract interface Waiter {
private void serve(Food aFood);
}
private static class AppetizerWaiter implements Waiter {
private void serve(Food aFood){
Appetizer appetizer = (Appetizer) aFood;
//somecode
}
}
private static class EntreeWaiter implements Waiter {
private void serve(Food aFood){//somecode}
}
private static class BeverageWaiter implements Waiter {
private void serve(Food aFood){//somecode}
}
private static class DessertWaiter implements Waiter {
private void serve(Food aFood){//somecode}
}
}

Try something similar to the following:
public serveItems(Food[] items)
{
for(Food aFood : items){
Class<?> foodClass = aFood.getClass(); // Get the food's class
Method serve = WaiterUtility.class.getMethod("serve", foodClass); // Get the method by name and argument types
try {
serve.invoke(this, aFood);
} catch (IllegalArgumentException e) { // Should never occur, we're matching it up.
} catch (IllegalAccessException e) { // Shouldn't occur, we're in the same class.
} catch (InvocationTargetException e) {
// Handle errors possibly thrown by the serve method.
}
}
Haven't tested this tho.
Note that you should however avoid this, it's terrible design.

Related

How to implement a subclassable Singleton in Java

I am looking for a way to implement an abstract class (or effectively abstract) that enforces only one instance of each subclass.
I am fairly sure this would be pretty simple to implement with a Factory but I would be interested to know if it can be done without knowing all subclass types, i.e a generic singleton enforcer class.
Right now I am mostly just playing around with the idea for something like this, So I am not looking for feedback that questions the design choice here.
The language I am working in is Java, but right now I am not necessarily worried about implementation details, Unless it is not possible in Java, then, of course, provide evidence that it is not possible.
I'm wondering what it is you are trying to do. A couple of possibilities spring to mind and knowing where this is heading might help.
Option 1
So you could try to use an enum type as your abstract base class. Each enumeration constant is then guaranteed by the language to be a singleton. The enum can have abstract methods which the constants implement. This will work but compilation unit an get very big and hard to navigate if you have a lot of implementing constants and a lot of abstract methods to implement. You could of course delegate some of the work to helper classes if it starts to get out of hand.
Option 2
You could do is get the base class constructor to check it's actual type and store it in a static HashSet (or similar). If an entry already exists then you have two instances of the same singleton. Something like
public abstract class BaseClass {
private static HashSet<Class<?>> instances = new HashSet<>();
protected BaseClass() {
checkInstances();
}
private synchronized void checkInstances() {
boolean duplicate = instances.add(getClass());
if (duplicate) {
throw new RuntimeException("Duplicate class " + getClass().getName());
}
}
}
The disadvantage of this is that the error occurs at runtime and the code isn't especially pretty and as you can see you may need to consider synchronization of the set
Option 3
Your final option is simply not to ask the base class to enforce this restriction. It should probably the job of the derived classes to decided if they are singletons or not. A private constructor in the derived class is the easiest way to do that.
Conclusion
Personally I'd implement either option 1 or option 3 as you won't get run-time failures.
First, a generic singleton doesn't make sense.
A parent class should not be responsible of retrieving and managing instances of its subclasses.
It creates a strong coupling in both ways (parent->child and child->parent).
Second, as shmosel says, subclassing a singleton (without special artifact) is not possible.
The key of the singleton pattern is the lack of ability to instantiate the class outside the singleton class, so no public constructor has to be provided.
In these conditions, how subclass the singleton class ?
To allow subclassing a singleton class, you must have a public constructor while ensuring that you have no more than one instance of the class.
Inversion of control containers such as Spring may do that (It is an example of special artifact).
As a side note, I don't consider access modifier tweaking such as the package-private modifier that could allow to subclass a singleton but the limitation of it is that the singleton would be a singleton only outside the package.
I wanted to say, that singletons are bad. But found this problem interesting, So I created what you want.
Here is the code
public static abstract class SingletonBase {
private static HashSet<SingletonBase> instances = new HashSet<>();
{
for (SingletonBase sb : instances) {
if (sb.getClass() == this.getClass()) throw new RuntimeException("there is already 1 instance");
}
}
public static <E> E getInstance(Class<E> clazz) {
if (!SingletonBase.class.isAssignableFrom(clazz)) {
throw new RuntimeException();
}
for (SingletonBase sb : instances) {
if (sb.getClass() == clazz) return (E) sb;
}
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private SingletonBase() {
instances.add(this);
}
}
static class SingletonTest extends SingletonBase{
}
static class SecondSingletonTest extends SingletonBase{
}
public static void main(String[] args) {
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SingletonTest.class));
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SecondSingletonTest.class));
//throws exception, because we try to create second instance here
new SingletonTest();
}
There are some problems with approach of creating generic class which are solved here:
first, you cannot create more than one instance, so base class has to keep track of all instances, and when you try to create another one using new, it will throw exception. Second, you need to get instance for a specific class. If you dont want to create instance like this:
SingletonBase.getInstance(SecondSingletonTest.class)
You can create subclasses like this:
static class SingletonTest extends SingletonBase{
public static SingletonTest getInstance(){
return getInstance(SingletonTest.class);
}
}
There was also suggested to use ENUM approach, it is easy to implement, but breakes open closed principle from SOLID

Alternatives to "Extending" Java Enums

I'm doing a very dumbed down ALife-esque application, and I which to have the following classes with the following inheritance relationship:
(Abstract)Lifeform <-- Plant
(Abstract)Lifeform <-- Animal
Plants and Animals share some states, and I'd ideally like this behavior to live in rudamentary form within Lifeform.
abstract class Lifeform
{
public static enum State
{
IDLE,
DEAD
}
protected void someMethodSomewhere()
{
....
state = State.IDLE; // this to be recognized by inherited creatures
....
}
protected State state;
}
class Plant extends Lifeform
{
public Plant() { state=new Plant.State(); }
public static enum State extends Lifeform.State // (can't)
{
FEEDING,
REPRODUCING,
}
}
class Animal extends Lifeform
{
public Animal() { state=new Animal.State(); }
public static enum State extends Lifeform.State // (can't)
{
FEEDING,
FORAGING,
FLEEING,
GROUPING,
REPRODUCING
}
// elsewhere in some method
public void someMethod()
{
switch(state)
{
case IDLE: (...) // from Lifeform.State
case FEEDING: (...) // from Animal.State
case DEAD: (...)
....
}
}
}
Is there a facility in the later (1.5+) java's that allow for something similar to this, or am I best off embedding this state hierarchy within it's own traditional class?
I don't think this is an enum problem as much as it is a state machine problem.
You have the name State which to me implies that you are actually working with a state machine. I would not use enum for this and actually model a proper state machine.
From the states that you have posted in your question, they imply a finite state machine as well. I think you are just going to implement some sort of state machine around these enums as an end result and should just go ahead and start where you are going to end up eventually.
I have used state machine compiler to great effect in the past to make creating and managing the state transitions simply.
Ragel looks like a good solution as well.
The only way you can do what you want is to roll your own pre-1.4 TypeSafe Enum
Before Java had enum as a type, I used a Type Safe Enum Pattern template in my IDE to create what was actually a richer implementation of what ended up in the language.
It is essentially just a Java class with final instance members and a private constructor and public final static instances of itself.
I will still warn that extending enum is not allowed for a very good reason and trying to work around it will probably give you more grief than it will solve.
Here is the solution I've used for years, in case it helps someone. I've rewritten it somewhat.
Note: It purposefully does not implement value support. This is not a difficult change, and frankly, I don't use them, so I pulled it out. I also rewrote it from my originally ancient version.
Note: I'm primarily supplying it here because it contains toString() support to yield the field name (no matter what you've used) from any subclass.
I've also specified field errors due to access restrictions to be a catastrophic (execution ending) error. You can modify this to be any exception handling you choose, but I would suggest you leave it as is.
package tgm.utils;
import java.lang.reflect.Field;
public abstract class InheritableEnum
{
protected InheritableEnum() {}
public String toString()
{
String returnStr = "Unknown InheritableEnum["+super.toString()+"]";
Field[] fields = this.getClass().getFields();
for (Field f : fields)
{
try
{
if (f.get(this) == this)
{
returnStr = f.getName();
break;
}
}
catch(IllegalAccessException e)
{
System.err.println("Illegal access on field["+f+"]");
e.printStackTrace();
System.exit(-1);
}
}
return returnStr;
}
}
Then you would use it similarly:
public class State extends InheritableEnum
{
public static final State DEAD = new State();
public static final State EATING = new State();
public static final State GROWING = new State();
}

Software design for adding aspects dynamically without AOP Framework

I have written a little example program to measure the time execution of java methods.
I want to design a solution which is low coupled and which can be added to other methods dynamically, which means that if I wrote other classes with other methods, I want to wrap my performance measuring module over my business logic module and measure the time execution of the methods while the business logic class has no dependencies to the performance measurement module.
My current solutions looks like this
I have an abstract class which defines some list operations.
I have sub-classes which defines the concrete list operations
I have a performance Measurement Class which extends the class which shall be measured
public abstract class ListOperations<T> {
private List<T> list;
public ListOperations() {
initList();
}
/**
* Initializes the list. Clients can decide which list type shall be used (e.g LinkedList, ArrayList etc.)
*/
public abstract void initList();
public abstract void addLast(final T element);
public List<? super T> getList() {
return list;
}
protected void setList(final List<T> list) {
this.list = list;
}
}
public class LinkedListOperations<T> extends ListOperations<T> {
public LinkedListOperations() {
super();
}
#Override
public void addLast(final T element) {
getList().addLast(element);
}
#Override
public void initList() {
setList(new LinkedList<T>());
}
#Override
public LinkedList<? super T> getList() {
return (LinkedList<? super T>) super.getList();
}
}
public class PerformanceMeassuredLinkedListOperations<T> extends LinkedListOperations<T> {
private static final String START_PERFORMANCE_MEASSURE_FOR_METHOD = "Start Performance Meassure for method: ";
private static final String STOP_PERFORMANCE_MEASSURE_FOR_METHOD = "Stop Performance Meassure for method: ";
private static final String TIME_EXECUTION_IN_MILLIS = "Time Execution in Millis: ";
/**
* Used to printout the name of the method from the stack. in depth 2 the real business logic method is located
*/
private static final int DEPTH_IN_STACKTRACE = 2;
// depth 0 = printStopMeassurement
// depth 1 = stopPerformanceMeassure
// depth 2 = method for which performance is measured (e.g addLast)
private long startCurrentTimeMillis;
#Override
public void initList() {
startPerformanceMeassure();
super.initList();
stopPerformanceMeassure();
}
public void meassureAddLast(final int numberOfElements, final T testElement) {
startPerformanceMeassure();
for (int i = 0; i < numberOfElements; i++) {
addLast(testElement);
}
stopPerformanceMeassure();
}
protected void startPerformanceMeassure() {
printStartMeassurement();
startCurrentTimeMillis = System.currentTimeMillis();
}
private void printStartMeassurement() {
System.out.println(START_PERFORMANCE_MEASSURE_FOR_METHOD + getNameOfCurrentExecutedMethod());
}
protected void stopPerformanceMeassure() {
System.out.println(TIME_EXECUTION_IN_MILLIS + (System.currentTimeMillis() - startCurrentTimeMillis));
printStopMeassurement();
}
private void printStopMeassurement() {
System.out.println(STOP_PERFORMANCE_MEASSURE_FOR_METHOD + getNameOfCurrentExecutedMethod());
}
private String getNameOfCurrentExecutedMethod() {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[ste.length - DEPTH_IN_STACKTRACE].getMethodName();
}
}
public class Main {
public static void main(String[] args) {
PerformanceMeassuredLinkedListOperations<String> listOperations = new PerformanceMeassuredLinkedListOperations<String>();
listOperations.meassureAddLast(50000, "Hello");
}
}
With this solution I must extend every business logic module and add my time measurement code in a static way.
Now I want to design a performance measure module that can be added dynamically to any business logic module and measures the performance of the methods called. I don't want to use any AOP Framwork for that. I think such a dynamical aspect addition can be done with a mixture of some kind of decorator and interceptor pattern but I have no idea how.
What you're describing is a cross cutting concern
Your needs fall squarely into the realm of an aspect. You want to be able to log latency across various cut-points in your code.
Consider:
Method 1
You will need to intercept all calls to said business modules.
You can define an BussinessModule interface. Create a delegate class that intercepts this common call and then wraps an abstract method and logs latency (or whatever).
It's limited but, with some effort can work and it's the easiest implementation.
Method 2
Develop some sort of expressive language to say which methods you want to intercept on what classes
Figure out a way to intercept those method calls (Without using AspectJ, or writing your own class-loader, I can't imagine how) and execute them
Method 1 is not at all dynamic. You must have iron control of implementation across your whole system. Any class that doesn't get included in your delegate/proxy scheme won't get this behavior. Someone has to make sure that every class implemented has this wrapper on it.
Method 2 is super dynamic. By having an expressive language/syntax you can describe code to get wrapper and then, even if it's not your code or you're working with lazy people, it still gets wrapped. The downside is that it would be insanely difficult and time consuming to implement. Good new though! Spring AOP and AspectJ already do this!
So, your question was
how do I do this without Spring AOP or AspectJ
I believe I have given an answer. But to be totally clear: Lots-and-lots of delegation would be the easiest route.
That said: There is no good explainable reason to roll your own. I literally have an Aspect and the bean config for Spring to do exactly this. If it's a question of time I can simply paste it in and you can rip it off and run with it.
You do not want to use a proven and tested framework because you alone can do better and exchange one framework for another - your own one. Be it as it may, you will be ending up using a framework. Does that make sense?
Good luck for re-inventing the wheel.
Update: Some more background about why I think you will be ending up implementing your own AOP framework: AOP is kind of orthogonal to OOP's inheritance concept. An OOP language without any semantic extensions like AspectJ or frameworks like Spring AOP just does not offer the means to express aspects, otherwise AOP languages/frameworks would be redundant. I doubt you will be able to solve the problem by a mere combination of two or so OOP design patterns.
Update 2: If you fail with design patterns and byte code generation is too complex for you, you might want to use the same approach as Spring AOP: Java dynamic proxies (works for interfaces) and/or CGLIB dynamic proxies (for non-interface types).

How do I reduce delegation boilerplate?

I have a class that implements an interface. There's another class that implements this interface, too, and an instance of this second class backs my class's implementation.
For many of the methods specified by the interface, my class simply forwards them straight to the second class.
public class MyClass implements MyInterface
{
private OtherClass otherClassInstance; // Also implements MyInterface.
// ...
void foo() { otherClassInstance.foo(); }
void bar() { otherClassInstance.bar(); }
void baz() { otherClassInstance.baz(); }
// ...
}
Simply deriving my class from the second class would eliminate all of this, but it doesn't make sense because the two classes are unrelated to each other (besides implementing a common interface). They represent different things - it just so happens that a lot of my class's implementation copies that of the other class. In other words, my class is implemented atop the second class, but it is not itself a subset of the second class. As we know, inheritance is meant to express an "is-a" relationship, not to share implementation, so it's inappropriate in this case.
This portion of a talk by Joshua Bloch illustrates the situation well.
I know that Java doesn't have any language support for delegation. However, is there at least some way to clean up my class's implementation so it isn't so redundant?
An answer which is not really an answer to your actual question:
I'd say, live with the boilerplate. Let IDE generate it for you. Example: in Netbeans, add the private ArrayList field, set cursor to where you'd want the methods to appear, hit alt-insert, select "Generate Delegate Method...", click the methods you want to create a delegate for in the dialog opens, submit, go through the generated methods and make them do the right thing, you're done.
It is a bit ugly, but it is still preferable to starting to mess with reflection, when you are dealing with just one class, like it sounds. Your class is probably the kind of class, which you will complete and fully test, and then hopefully never touch again. Reflection creates runtime cost which does not go away. Suffering the auto-generated boilerplate in the source file is probably preferable in this case.
First way to use http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html see tutorial http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html
Second way using AOP you can create dispatcher that intercept all invocation of specific class
For both ways you need to manage methods processing using reflection API
EDITED TO SHOW IDEA
Following code taken from tutorial above just modified a little (see youListImpl.getRealArrayList() in invoke method)
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private YouListImpl youListImpl;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
System.out.println("before method " + m.getName());
result = m.invoke(youListImpl.getRealArrayList(), args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}
}

How to hide a public method?

I have a method in my static state machine that is only used once when my application is first fired up. The method needs to be public, but I still want it hidden. Is there a way to use an annotation or something that will hide the method from the rest of the project?
You cannot make a public method hidden (unless you can declare it private). You can however put in a subclass and only let the users of the object know the type of the superclass, that is:
class A {
//Externally visible members
}
class B extends A {
//Secret public members
}
Then you instantiate the class B, but only let the type A be known to others...
Once you declare public method it becomes part of your class's contract. You can't hide it because all class users will expect this method to be available.
You could use package level instead of public. That way it can only be called by your application.
If a method is public, it can't be hidden. What you may really be looking for is just a way to restrict access to calling a method. There are other ways to achieve a similar effect.
If there are some things that your state machine does that are "only used once when my application is first fired up" it sounds a lot like those are things that could happen in the constructor. Although it depends on how complex those tasks are, you may not want to do that at construction time.
Since you said your state machine is static, is it also a Singleton? You could maybe use the Singleton Pattern.
public class SimpleStateMachine {
private static SimpleStateMachine instance = new SimpleStateMachine();
private SimpleStateMachine() {
super();
System.out.println("Welcome to the machine"); // prints 1st
}
public static SimpleStateMachine getInstance() {
return instance;
}
public void doUsefulThings() {
System.out.println("Doing useful things"); // prints 3rd
}
}
Here's some code for a client of this Singleton:
public class MachineCaller {
static SimpleStateMachine machine = SimpleStateMachine.getInstance();
public static void main(String... args) {
System.out.println("Start at the very beginning"); // prints 2nd
machine.doUsefulThings();
}
}
Note that the SimpleStateMachine instance isn't built until the first time your class is accessed. Because it's declared as static in the MachineCaller client, that counts as a "first access" and creates the instance. Keep this tidbit in mind if you definitely want your state machine to perform some of those initialization tasks at the time your application starts up.
So, if you don't want to turn your state machine class into a true singleton... you can use a static initialization block do your one-time tasks the first time the class is accessed. That would look something like this:
public class SimpleStateMachine {
static {
System.out.println("First time tasks #1");
System.out.println("First time tasks #2");
}
public SimpleStateMachine() {
super();
System.out.println("Welcome to the machine");
}
public void doUsefulThings() {
System.out.println("Doing useful things");
}
}
While we're at it, since you mentioned that it's a state machine... the Head First Design Patterns book does a nice, easily understandable treatment of the State Pattern. I recommend reading it if you haven't already.
The idiomatic approach to doing this is to use interfaces to limit the visibility of your methods.
For example, say you have the following class:
public class MyClass {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
If you want to limit some parts of the project to only see method1(), then what you do is describe it in an interface, and have the class implement that interface:
public interface Method1Interface {
public void method1();
}
...
public class MyClass implements Method1Interface {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
Then, you can limit the visibility of the methods by choosing to pass the class around either as a MyClass reference, or as a Method1Interface reference:
public class OtherClass {
public void otherMethod1(MyClass obj) {
// can access both obj.method1() and obj.method2()
}
public void otherMethod2(Method1Interface obj) {
// can only access obj.method1(), obj.method2() is hidden.
}
}
A bonus of this approach is that it can also be easily extended. Say, for example, you now also want to independently control access to method2(). All you need do is create a new Method2Interface along the same lines as Method1Interface, and have MyClass implement it. Then, you can control access to method2() in exactly the same manner as method1().
This is a similar approach to that advocated in #MathiasSchwarz's answer, but is much more flexible:
The independent access control described in the preceding paragraph isn't possible with Mathias' technique, due to Java not supporting multiple inheritance.
Not requiring an inheritance relationship also allows more flexibility in designing the class hierarchy.
The only change required to the original class is to add implements Method1Interface, which means that it is a very low-impact refactor since existing users of MyClass don't have to be changed at all (at least, until the choice is made to change them to use Method1Interface).
An alternative solution: You can make it private and create a invokeHiddenMethod(String methodName, Object ... args) method using reflection.
You said that your public method is used only once when the application is started up.
Perhaps you could leave the method public, but make it do nothing after the first call?
There is a (non-)keyword level package level visibility. Instead of public, protected, or private, you use nothing.
This would make the method or class visible to the class and others in the package, but would give you a certain modicum of privacy. You may want to look at What is the use of package level protection in java?.
Hmm... You want a private method, but want to access it outside?
Try do this with reflection.
http://download.oracle.com/javase/tutorial/reflect/index.html
I have seen many Java programmers do something like this:
public static void main(String args[]) {
new MyClass();
}
So basically they create just one object of the class. If there is a method which should run only once, I guess this approach can achieve that. Your method will be called from inside the constructor. But since I don't know how your app works, what are the constraints, so it is just a thought.

Categories