How to make any Java method static at run time? - java

I am wondering if there is any way to achieve the following.
Find a method using reflection (done)
Change the method access modifier to to public and static. (How?)
execute this method without having any existing instance (How?)
Does reflection has any option to do this?

No, this is completely impossible and makes no sense whatsoever. An instance method has access to (and typically uses) instance variables. What should e.g. a typical set or get method that has been "made static" possibly do?

This doesn't make any sense. A non-static method is non-static for a reason, in that it needs to access member data specific to a particular instance of the class. How would you convert that to static?

Even if you used tools that let you change a class (like BCEL), you still wouldn't have achieved anything, because (all minor caveats aside) the moment you change a method from instance method to static, all code calling it will throw a NoSuchMethodError. The reason being that invoking a static/instance method use two different opcodes.

No. You can't change a class with reflection. You can just inspect it.

I don't think it's possible.
If your method uses a 'this' reference, that would be an undefined behaviour.

As all said this is bad and should not be done.
But again if you have to achieve this and you have already given the reason so I might like to try something different to achieve this.
I might create a singleton class and give a static method (facade) to access the required API method and always make sure that all other classes use this singleton class method to access the API method.

Related

Under what circumstances should my Java class have a constructor (and not rely on the default constructor)?

I went through a coding problem in a course I'm taking, and I didn't realize that I needed to include my own constructor until I saw the instructor's solution. This has happened a few times throughout the course: I don't expect that I need a constructor, but it turns out I do need one, according to the answer given (below is one of the answers given to me).
I'm wondering now: do I need to make my own constructors when I need to pass parameters and/or I need additional functionality inside the constructor? Are there other situations when relying on the default constructor would be problematic?
private MenuIterator() {
menuIterator = menu.iterator();
calculateNumMenuItems();
}
You need a constructor exactly when you need to perform some sort of setup for your class and field initialization isn't enough. Your described constructor makes no sense because there's no way for your constructor to get menu (and the private modifier prevents you from calling new MenuIterator() in the usual fashion).
The answer given by chrylis is correct. You may also find this discussion of default constructors useful: Java default constructor. Essentially, if you provide any constructor at all (even a no-arg constructor), you will no longer be provided with a default constructor.
If you need to do anything other than call the class' superclass constructor, you will need to supply your own constructor.
Maybe slightly advanced. In addition to what #chrylis said you also need an explicit constructor if you need the constructor to be anything else than public. This is the case if you want the clients of your class to obtain an instance through a static factory method and not use the constructor directly. The Singleton pattern is just one of many uses of a static method for obtaining an instance.
I wouldn’t worry too much. Even though your instructor has a fine solution with a constructor, it could well be that you have a fine solution without a constructor. Programming problems can always be solved in more than one way.
Links
Java Constructors vs Static Factory Methods
Singleton pattern

Java - "super" , "this" or neither - good practice

As far as I understand, this can be used inside a class to call a method available in any of its superclass as the compiler will look for the method in its superclasses if it's not available in the (sub)class. Basically just like using a super.
So I was wondering, which is the better way of doing things? Is there a general rule of thumb for sing either?
QUESTION:
When the method in question is not coded i.e only available via inheritance from its super class) in the (sub)class, they basically do the same thing right? In that case, is there a reason to pick one over the other?
super.methodAvailableInSuper();
or
this.methodAvailableInSuper();
MORE CLARIFICATION
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
They're not equivalent, so your question isn't meaningful.
this.method() will invoke the most-derived override of method(), including in any derived classes that this object may be an instance of
super.method() will invoke the base class's implementation of method(), or whatever implementation it inherited if it doesn't provide an implementation itself.
You should use whichever one does exactly what you want. It's not just an aesthetic choice, or a question of 'good practice'.
EDIT Re your edited edit:
When the method in question is not available in base class, they basically do the same thing right?
Wrong. super always calls a method in the base class or one of its parents. this calls the most-derived override. You would write super if you definitely didn't want to call any future implementation in any future derived class, and you would write this, or nothing, if you did want to call such an implementation if it exists when the call is made. Which is not something you can know when coding.
This is not a question of "best practice" since these keywords are very different.
When you call super.methodAvailableInSuper(); then all parent classes are searched for this method at runtime. If this method exists in the current class or any subclass, this method wont be executed.
You can use this, if you want to call the super implementation of an overriden method without cousing an endless loop.
The keyword this calls the method on the current object. Thus the normal execution of methods will be performed.
See also:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.

Possible to have a function thats not a method in java?

In this Java program I'm writing I’m finding that I’m clogging up the main() method with a lot of code that would make it hard to quickly understand/read. Specifically due to a lot of error checking that I’m doing. As a result I want to write a quick function that is only going to be used by this one method to improve readability.
Is writing another method within the class my only option or are there other alternatives?
Is writing another method within the class my only option or are there other alternatives?
It depends:
If the methods should belong only to this class, they should be declared as private or protected methods in the class, depending if the class can be inherited or not.
If the methods should be reused in other classes, it would be better to move it to utility classes as public. For example, check if a String is empty and also validating if is not null. Note that for this example there are methods covering these validations in utility classes from Apache Common Langs, explicitely StringUtils#isEmpty(String).
By the way, Java has methods, no functions.
Answer is yes, generally private methods in the classes hold the code which is not used by outside world. But havig private methods help to reduce the cyclomatic complexity of your public methods. Smaller methods lead to more readable and understandable methods.
Since Java was designed that way, you can only have methods. So, yes, that's the only way. Usually you would use class methods (static) for instance independent methods. These can also be within another class, for example a utility or helper class.

Is there any harm in using super when not needed?

This message pertains strictly to Java. If a method is in a superclass there are two ways the method could be called:
foo();
super.foo();
Is there any harm in always doing the latter? As a coding style I prefer the latter because it's clear at a glance where the method call is coming from. Are there any circumstances where 'super' is going to be non-existent or not do what I think it would do?
I think the only harm you may have is when you want to use polymorphism so, if you call foo() and some subclass overrides foo, then the effect would be different than if you call super.foo(), basically, it depends on how you are designing the code and for what purpose.
Hope this makes it clear.
As a general rule, you should only use super.foo() inside your class foo() method. Doing otherwise, in general, goes against OOP thinking.
because it's clear at a glance where the method call is coming from
In OOP you should'n want to know where the method call "comes from". If your program (or your thinking) is depending on that, you are in potential trouble (and will probably be in actual trouble when someone decides to override the method). The method myobject.foo() must be seen from the outside as the method of the myobject's class; it should not matter if that method is implemented actually in the concrete class of its parent.
I would say there is more harm in doing the former as it's not clear that it's a method of the superclass.
Yeah this basically breaks the inheritance chain.
You don't allow the inheritance mechanism to choose what function to use even in classes derived from this one.
The point of super.foo() is to allow you to specify only when it is needed and you know no other behavior will be good.
If you do not want to explicitly avoid using an overriding method in the subclass then you should not use super.
Always using super might cause trouble if later on someone wants to override the method in the subclass.
That's a preferable way if you intend to call the method on the super class, instead of calling foo() without super.. If anyone does overwrite foo() in the subclass the super call does call the same method as before, but omiting super will now call the overwritten method. It depends on what you intent with that method call.
It depends.
If foo() is declared as final, it will make no difference at all. If foo() is not declared as final, then a subclass could override the declaration of foo() in your superclass and completely change the expected behaviour.
If you make your own class final, you can prevent it from being sub-classed, and be certain the original intent is preserved.
I would be say that this might indicate that you should think over you design again.
If you are always calling the functionality by super.foo() then you block yourself from overriding the function later, and if you don't want to have the ability to override the function, then maybe you shouldn't use inheritance as a method for accessing this functionality.
One design principle that I have heard banded about is "favour composition over inheritance", the reason for this is that your code becomes more flexible with composition rather than inheritance. And if you don't gain the positive aspects of inheritance (being able to override the function) then maybe it's wiser to not use inheritance.

Can I Instantiate a class using the class object? What about Constructors?

I am storing a list of classes through (Classname.class) and would like to instantiate one? Is this possible?
newInstance seems to the method I am after but it doesn't support a constructor?
You can use Class.getConstructors (or Class.getConstructor) to get a list of available constructors, and invoke any of them with Constructor.newInstance, which does accept parameters.
Just to add one point I see missing:
You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)
Otherwise, you can find constructors via Class.getConstructors() as others have said.
The Java tutorial on reflection covers this well. But yeah, basically Class.getConstructors, then Constructor.newInstance is where it's at.
Java is designed so you can never "trick" it as long as you use the java.lang/java. classes or other standard libraries. One of the most important things of OOP is that objects should be in a defined state, thus you can be safe that the constructor is always run. Even if you're using some strange-looking reflection libraries to get your work done.
So, using Class.forName("me.Test").newInstance(); (or similar) will under-the-hood invoke the Test() constructor for you.
If you want to invoke another constructor the code is something like:
Test test = (Test)Class.forName("Test").getConstructor(String.class).newInstance("Hello World");
Here the getConstructor asks what the constructor looks like (it wants a string) and then you call it with a string.
You cannot construct new classes this way.
If you have the name of a class you can use Class.forName(className) to load/reference a class.
If you have the byte code for a class you want to create you can have a class loader load the byte code and give you the class. This is likely to be more advanced than you intended.
If you have a list of Class objects obtained through class literals, you might as well statically reference the constructors rather than slipping into reflection evilness.

Categories