Print statement not called in anonymous class passed to class constructor - java

I have two classes and one interface.
Interface:
public interface MyBirthdayEvent {
void itsMyBirthday();
}
First class:
public class MyBirthdayButton
{
public void addOnClickedListener(MyBirthdayEvent mbe){}
}
Second class:
public class MyBirthday {
private MyBirthdayButton myBirthdayButton = new MyBirthdayButton();
MyBirthday() {
myBirthdayButton.addOnClickedListener(new MyBirthdayEvent() {
public void itsMyBirthday() {
System.out.println("Happy Birthday");
}
});
}
}
Then in main, I have this:
public class TestThisStuff {
public static void main(String[] args) {
MyBirthday myBirthday = new MyBirthday();
}
}
As can be seen from the code, I am using an anonymous class in the MyBirthday constructor. In doing so, I am trying to get the string "Happy Birthday" to print to the console.
My problem is, when I call the MyBirthday constructor in main by making a new myBirthday object, I am not seeing the string "Happy Birthday" print to the console. Shouldn't it print to the console? If not, what I am doing wrong?

What you can do is this:
public interface MyBirthdayEvent {
void itsMyBirthday();
default void invoke() {
itsMyBirthday();
}
}
...
public class MyBirthdayButton
{
public void addOnClickedListener(MyBirthdayEvent mbe){
mbe.invoke();
}
}
...
Also, it will work without it, but use a lambda rather than an anonymous inner class. This looks much better.
MyBirthday() {
myBirthdayButton.addOnClickedListener(() ->
System.out.println("Happy Birthday"));
}

you can move System.out.println("some words")statement to your MyBirthdayEventconstructor
it didn't show in your console because you haven't invoke the method

Related

Is there a way to re-declare a method from an other class?

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.

Gauge - run #BeforeSpec in a superclass in Java

I am writing a testing framework using Gauge.
I want some initilization logic performed in one class, and the steps logic to reuse it, like this:
public class A {
protected String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B extends A {
#Step("...")
public void verifyProperty() {
assertEquals(property, "hello");
}
}
I can't seem to be able to achieve this. When performing the steps, the "property" is always null.
Placing the #BeforeSpec in class B and calling super.init() works, but I would like to avoid having this call in every test class that extends A.
Has anyone encountered and solved such an issue?
Try to use a static variable:
public class A {
public static String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B {
#Step("...")
public void verifyProperty() {
assertEquals(A.property, "hello");
}
}

Best way to pass a variable from outer class to inner class

I'm building an android app (but this is not important for the post) and I'm writing a method called scrollUntilSelectedAvatar() that contain a class:
public class AvatarManager {
private HorizontalScrollView avatarPageHorizontalScrollView;
//mehod that contains the inner class
public void scrollUntilSelectedAvatar(HorizontalScrollView avatarPageHorizontalScrollView){
this.avatarPageHorizontalScrollView = avatarPageHorizontalScrollView;
avatarPageHorizontalScrollView.post(new Runnable() {
#Override
public void run() {
AvatarManager.this.avatarPageHorizontalScrollView.scrollTo(100, 0);
}
});
}
}
My question is: what's the correct way to access avatarPageHorizontalScrollView (that I pass to the method as an argument) inside the inner class new Runnable().
The way I found (AvatarManager.this.avatarPageHorizontalScrollView) doesn't seems the best way.
Thank everybody for the help :)
The way you did it - is the one and only correct. Syntax of some thing about inner classes may seem quite strange. But it is just like it is.
public class A {
private int a;
private abstract class B {
public abstract void printA();
}
public B makeB() {
return new B() {
#Override
public void printA() {
System.out.println(A.this.a);
}
};
}
}

Java: Is it possible to always execute a certain function before other functions are called? (Like #Before in JUnit)

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

Java8 pass a method as parameter using lambda

I would like to create a class that store a list of methods references and then executes all of them using Java 8 Lambda but I have some problem.
This is the class
public class MethodExecutor {
//Here I want to store the method references
List<Function> listOfMethodsToExecute = new LinkedList<>();
//Add a new function to the list
public void addFunction(Function f){
if(f!=null){
listOfMethodsToExecute.add(f);
}
}
//Executes all the methods previously stored on the list
public void executeAll(){
listOfMethodsToExecute.stream().forEach((Function function) -> {
function.apply(null);
}
}
}
This is the class that I created for test
public class Test{
public static void main(String[] args){
MethodExecutor me = new MethodExecutor();
me.addFunction(this::aMethod);
me.executeAll();
}
public void aMethod(){
System.out.println("Method executed!");
}
}
But there is something wrong when I pass this::aMethod using me.addFunction.
What is wrong?
You should provide a suitable functional interface which abstract method signature is compatible with your method reference signature. In your case it seems that Runnable instead of Function should be used:
public class MethodExecutor {
List<Runnable> listOfMethodsToExecute = new ArrayList<>();
//Add a new function to the list
public void addFunction(Runnable f){
if(f!=null){
listOfMethodsToExecute.add(f);
}
}
//Executes all the methods previously stored on the list
public void executeAll(){
listOfMethodsToExecute.forEach(Runnable::run);
}
}
Also note that in static main method this is not defined. Probably you wanted something like this:
me.addFunction(new Test()::aMethod);
You can't refer to this in a static context as there is no this
me.addFunction(this::aMethod);
You need to refer to an instance or define your Function to take a Test object.
public void addFunction(Function<Test, String> f){
if(f!=null){
listOfMethodsToExecute.add(f);
}
}
and
me.addFunction(Test::aMethod);

Categories

Resources