This might not have a solution, or I might have not been able to find one, but here it is:
!! Note: the code below is incorrect, I know. I just want to show what exactly I would like to accomplish.
I would like to do something on the lines:
public class ActionBarHandler{
public static ActionBarHandler withAddOption(){
//do something ...
return ActionBarHandler;
}
public static ActionBarHandler withEditOption(){
//do something ...
return ActionBarHandler;
}
}
... in order to do the below somewhere in another class (i.e. have it in a single line):
//..
ActionBarHandler.withAddOption().withEditOption().with........;
//..
... instead of doing this:
//..
ActionBarHandler.withAddOption();
ActionBarHandler.withEditOption();
ActionBarHandler.with........;
//..
Can this be done in any way? With static methods, without having an instance of the class.
Yes, declare the method as
public static ActionBarHandler withAddOption(){
and simply return null.
But I don't recommend this. Use objects with method chaining. From a conceptual standpoint, it doesn't make sense to invoke a static method on an instance, even less on a null reference. For that reason alone, you should consider refactoring your design to chain instance method invocations, ie. use objects.
You are describing the 'fluent interface' pattern. I think the best solution would be using the 'builder' pattern. Just google 'java builder pattern' and you will find tons of articles about it. It's really hard for me to choose a single article to show you.
Below code shows chaining unbounded Function method references. Static references can be no harder than that.
import java.util.function.Function;
public class TempTest {
public static class A {
public Void f1() { System.out.println("A.f1 called......."); return null; }
public Void f2() { System.out.println("A.f2 called......."); return null; }
public <T> T chain(Function<T, Void> f) { f.apply((T) this); return (T) this; }
}
public static class B extends A {
public Void f1() { System.out.println("B.f1 called......."); return null; }
public Void f3() { System.out.println("B.f3 called......."); return null; }
}
public static void main(String[] args) {
new A().chain(A::f1).chain(A::f2);
new B().chain(B::f1).chain(B::f2).chain(B::f3).chain(A::f1);
}
}
Output:
A.f1 called.......
A.f2 called.......
B.f1 called.......
A.f2 called.......
B.f3 called.......
B.f1 called.......
public class ActionBarHandler
{
public static Class<ActionBarHandler> withAddOption(){
//do something ...
return ActionBarHandler.class;
}
public static Class<ActionBarHandler> withEditOption(){
//do something ...
return ActionBarHandler.class;
}
}
Related
Sorry for the very noob question I'm new to this
For example let say I have this code:
public class Amazing {
public static void DoSomethingAmazing() {
System.out.println("I did something amazing");
}
}
public class MainClass {
public static void main(String[] args) {
Amazing.DoSomethingAmazing();
}
}
Would it be possible for me to make so whenever Amazing.DoSomethingAmazing() is used it does something else (For example prints "I did not do something amazing" instead) without changing either the class the method is in or the class using it?
Closest you can get to this is by extending Amazing class and overriding DoSomethingAmazing method, e.g.:
public class Amazing {
public void DoSomethingAmazing() {
System.out.println("I did something amazing");
}
}
public class SomethingMoreAmazing extends Amazing {
public void DoSomethingAmazing() {
System.out.println("I did something more amazing");
}
}
In the main method, you can do this:
Amazing a = new SomethingMoreAmazing();
a.DoSomethingAmazing();
It will print I did something more amazing i.e. it will make DoSomethingAmazing do something else without changing it.
You can read more about method overriding here.
Recently I've been restructuring a Java code of mines trying to eliminate, wherever possible, static stuff (variables and methods) and replace it with better coding practices.
I also started studying reflection and noticed that it allows me to do some things1 that, at first, I could only achieve (or, at least, that's how I see it) with static calls or references.
However, while I've been reading that the use of static is not much recommended, it doesn't seem to be the same with reflection.
So, I'm asking: instead of making a method static and calling it like ClassName.methodName(), is it a legitimate use of reflection making it an instance method and invoking it by java.lang.reflect.Method.invoke()?
1 like dynamically accessing a class' content
Here's a code sample:
Hypothetic situation that works (but I don't want to make the method static):
import static java.lang.System.out;
public class Foo
{
private static boolean light;
public Foo()
{
turnOn();
}
public static void turnOn()
{
light = true;
}
public static void turnOff()
{
light = false;
}
public static boolean isGreenLight()
{
return light;
}
}
public class Boo
{
public Boo()
{
if (Foo.isGreenLight()) // I need to access Foo.isGreenLight() from here, but cur-
{ // rently that method is not static (it should be to do so)
out.println("Ok!");
}
}
}
public final class Main
{
public static void main(String[] args)
{
final Boo boo = new Boo();
}
}
Hypothetic situation that also should work (how it'd be using reflection):
import static java.lang.System.out;
import java.lang.reflect.Method;
public class Foo
{
private boolean light;
public Foo()
{
turnOn();
}
public void turnOn()
{
this.light = true;
}
public void turnOff()
{
this.light = false;
}
public boolean isGreenLight()
{
return this.light;
}
}
public class Boo
{
public Boo()
{
if ((boolean) Class.forName("Foo").getMethod("isGreenLight", null).invoke(new Foo(), null))
{
out.println("Ok!");
}
}
}
public final class Main
{
public static void main(String[] args)
{
final Boo boo = new Boo();
}
}
Expected output (untested):
Ok!
Using reflection is a code smell, especially if the intent behind what you're writing does not warrant it.
It is difficult to say much more without seeing code as it's all just guesswork.
I would:
enumerate the reasons behind why you had those static members in the first place
determine if the static modifier was in fact the right decision in the first place: i.e. should these be instance or class members? How might they be used by "clients" of the classes in question? What paradigm am I using? Functional or Object Oriented code. Does it satisfy DRY, SOLID and KISS programming practices?
consider if I'm over-engineering in the first place
More importantly:
I would design my code through tests first, which drives the design of your API through the eye of the user, with the added benefit that you have test coverage before you've even implemented. Often times when writing code this way I eliminate such questions because the solution is more obvious when thought from the perspective of a user rather than a designer. It becomes a question of pragmatism rather than satisfying architectural design goals and philosophies.
Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx
I come from a Python background and in Python you can pass in the type of an object as a parameter. But in Java you cannot do this, any tips on how to get something like this working?
private void function(Type TypeGoesHere)
Stock s = new TypeGoesHere();
s.analyze();
}
Java does not support Python’s way of referencing functions and classes. To achieve this behaviour, you have to use two advanced techniques: generics and reflection. Explaining these concepts is beyond the scope of a SO answer. You should read a Java guide to learn about them.
Yet here is an example how this would look like, assuming that the given class has a no-argument constructor:
public <T extends Stock> void analyzeNewStock(Class<T> clazz) throws Exception {
Stock s = clazz.newInstance();
s.analyze();
}
Then call this function with analyzeNewStock(MyStock.class).
As this is a rather complicated and error-prone approach, you’d rather define an interface that creates Stock instances:
public interface StockProvider {
Stock createStock(String value);
}
public class MyStockProvider implements StockProvider {
private final String valueTwo;
public MyStockProvider(String valueTwo) {
this.valueTwo = valueTwo;
}
#Override
public Stock createStock(String valueOne) {
return new MyStock(valueOne, valueTwo);
}
}
public class MyOtherClass {
public void analyzeNewStock(StockProvider provider) {
provider.createStock("Hi!").analyze();
}
public static void main(String[] args) {
analyzeNewStock(new MyStockProvider("Hey!"));
}
}
In Java you can pass a Class. You can do it like this:
private void function(Class c)
This is not very common procatice though. You can probably get wha you need by looking into Strategy pattern, or proper use of Object Oriented Programming (polymorphism).
If you are looking for a way to build some objects, look into Factory pattern.
If you want to create a generic class- look into this detailed answer: https://stackoverflow.com/a/1090488/1611957
You could use generics. For example:
private <T> void function(Class<T> clazz) {
try{
T t = clazz.newInstance();
//more code here
}catch(InstantiationException | IllegalAccessException ex){
ex.printStackTrace();
}
}
The Class<T> clazz shows what type to instantiate. The try/catch is just to prevent errors from stopping your code. The same idea is expanded in this SO post. More info here.
However, I'm not really sure why you would want to do this. There should easily be a workaround using a simple interface. Since you already know that you want an object with type Stock, you could pass an implementation of the interface. For example:
//interface to implement
public interface Stock {
public void analyze();
}
//rewrite of function
private void function(Stock s){
s.analyze();
}
And using two ways to call function:
//first way
public class XYZ implements Stock{
public void analyze(){
//some code here
}
}
//calling the function
function(new XYZ());
//second way
function(new Stock(){
public void analyze(){
//your code here
}
});
I have FinanceRequests and CommisionTransactions in my domain.
If I have a list of FinanceRequests each FinanceRequest could contain multiple CommisionTransactions that need to be clawed back. Dont worry how exactly that is done.
The class below (very bottom) makes me feel all fuzzy and warm since its succint and reuses existing code nicely. One problem Type erasure.
public void clawBack(Collection<FinanceRequest> financeRequestList)
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
They both have the same signature after erasure, ie:
Collection<FinanceRequest> --> Collection<Object>
Collection<CommissionTrns> --> Collection<Object>
So eclipse complainst that:
Method clawBack(Collection) has the same erasure clawBack(Collection) as another method in type CommissionFacade
Any suggestions to restructure this so that it still an elegant solution that makes good code reuse?
public class CommissionFacade
{
/********FINANCE REQUESTS****************/
public void clawBack(FinanceRequest financeRequest)
{
Collection<CommissionTrns> commTrnsList = financeRequest.getCommissionTrnsList();
this.clawBack(commTrnsList);
}
public void clawBack(Collection<FinanceRequest> financeRequestList)
{
for(FinanceRequest finReq : financeRequestList)
{
this.clawBack(finReq);
}
}
/********COMMISSION TRANSACTIOS****************/
public void clawBack(CommissionTrns commissionTrns)
{
//Do clawback for single CommissionTrns
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
{
for(CommissionTrns commTrn : commissionTrnsList)
{
this.clawBack(commTrn);
}
}
}
Either rename the methods, or use polymorphism: use an interface, and then either put the clawback code in the objects themselves, or use double-dispatch (depending on your design paradigm and taste).
With code in objects that would be:
public interface Clawbackable{
void clawBack()
}
public class CommissionFacade
{
public <T extends Clawbackable> void clawBack(Collection<T> objects)
{
for(T object: objects)
{
object.clawBack();
}
}
}
public class CommissionTrns implements Clawbackable {
public void clawback(){
// do clawback for commissions
}
}
public class FinanceRequest implements Clawbackable {
public void clawBack(){
// do clwaback for FinanceRequest
}
}
I prefer this approach, since I'm of the belief your domain should contain your logic; but I'm not fully aware of your exact wishes, so I'll leave it up to you.
With a double dispatch, you would pass the "ClawbackHandler" to the clawback method, and on the handler call the appropriate method depending on the type.
I think your best option is to simply name the method differently.
public void clawBackFinReqs(Collection<FinanceRequest> financeRequestList) {
}
public void clawBackComTrans(Collection<CommissionTrns> commissionTrnsList) {
}
In fact, it's not too bad, since you don't get anything extra out of having the same name on them.
Keep in mind, that the JVM will not decide which method to call at runtime. As opposed to virtual methods / method overriding resolution of overloaded methods are done at compile time. The Java Tutorials on method overloading even points out that "Overloaded methods should be used sparingly...".
Here is a trick with overloading by the second varargs parameter for the CommissionFacade class from the question:
public class CommissionFacade {
public void clawBack(Collection<FinanceRequest> financeRequestList, FinanceRequestType ...ignore) {
// code
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList, CommissionTrnsType ...ignore) {
// code
}
/*******TYPES TO TRICK TYPE ERASURE*******/
private static class FinanceRequestType {}
private static class CommissionTrnsType {}
}
The code snippet to fast-check this trick works:
import java.util.ArrayList;
class HelloType {
public static void main(String[] args) {
method(new ArrayList<Integer>());
method(new ArrayList<Double>());
}
static void method(ArrayList<Integer> ints, IntegerType ...ignore) {
System.out.println("Hello, Integer!");
}
static void method(ArrayList<Double> dbs, DoubleType ...ignore) {
System.out.println("Hello, Double!");
}
static class IntegerType {}
static class DoubleType {}
}