Calling a method from an argument - java

I apologize if this is a duplicate question, I want to be able to call a method that is defined in the constructors argument list from a different method.
What follows is code that won't compile, but its really the only way I can think of describing my question. I also hope my explanation makes sense.
Main.java
....
Class0 instance = new Class0(arg0, arg1, arg2, new Class1(){
//do something
//do something else
//do more stuff
}
)
library.go(instance);
....
The point I want to get across here is that a new instance of Class0 is initialized with an anonymous function.
The instance is then passed to an instance of Library.
Class0.java
....
public Class1 action = null;
public Class0(int arg0, int arg1, int arg2, Class1 class) {
setArg0(arg0);
setArg1(arg1);
setArg2(arg2);
setAction(class);
}
public setAction(Class1 class) {
action = class;
}
public action() {
class;
}
....
Class0 is constructed from the constructor method and sets the function to the action field, it remains uncalled but stored for later.
action() calls the function passed into the constructor.
Library.java
....
public void go(Class0 class0) {
class0.action();
}
....
For the most part Library.java is out of my control, it is an conduit for a third-party library.
go calls the stored function of the instance object, declared in main, through its action method.
Does anything like this even remotely exist in java? Is there any other way to achieve the same thing?

Edit: This assumes java 7.0 or earlier. It works in java 8, but lambda expressions are most likely preferred.
It appears that you want to implement a callback interface.
create an interface with a method.
use the interface as a parameter to a method (constructor in your case).
the interface is just a reference to some object, so call the method.
Here is some code:
Kapow.java
public interface Kapow
{
void callbackMethod();
}
KapowImpl.java
public class KapowImpl implements Kapow
{
#Override
public void callbackMethod()
{
System.out.println("Kapow!");
}
}
Main.java
public final class Main
{
private static void callIt(final Kapow theCallback)
{
theCallback.callbackMethod();
}
public static void main(String[] args)
{
Kapow kapowObject = new KapowImpl();
callIt(kapowObject);
}
}

A good example of a "method type declaration" is java.awt.event.ActionListener (see below). In Java 8 or higher you can use use lambda expressions to simplify the usage, but the principle is still the same - an interface with one method declaration stands for the logical method.
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.awt.event;
import java.util.EventListener;
/**
* The listener interface for receiving action events.
* The class that is interested in processing an action event
* implements this interface, and the object created with that
* class is registered with a component, using the component's
* <code>addActionListener</code> method. When the action event
* occurs, that object's <code>actionPerformed</code> method is
* invoked.
*
* #see ActionEvent
* #see Tutorial: Java 1.1 Event Model
*
* #author Carl Quinn
* #since 1.1
*/
public interface ActionListener extends EventListener {
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e);
}
Here's a quick example on how to use that pattern:
public static void main(String[] args) {
ActionListener squeezeAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ouch!");
}
};
performAction(squeezeAction);
}
public static void performAction(ActionListener method) {
method.actionPerformed(null); //invoke method
}
With lambda expressions (requires JRE 1.8 or higher) this can be simplified to:
public static void main(String[] args) {
ActionListener squeezeAction = e -> System.out.println("Ouch!");
performAction(squeezeAction);
}
public static void performAction(ActionListener method) {
method.actionPerformed(null); //invoke method
}
Or as a reference to an existing method:
public class Test {
public static void main(String[] args) {
ActionListener squeezeAction = Test::squeeze;
performAction(squeezeAction);
}
public static void sqeeze(ActionEvent e) {
System.out.println("Ouch!");
}
public static void performAction(ActionListener method) {
method.actionPerformed(null); //invoke method
}
}

Related

How to subscribe to property in created object in java

I have a class which implement an interface from third part library and one of methods is passing object of class called Velocity.
How I can listen to specific variable value changes in this object?
Here is the code for better understanding.
This is interface from the third part library :
public interface MotionListener {
void onObjectMoved(Velocity velocity);
void onObjectStopped();
}
and the Velocity class is packed in the library and it is very simple.
The class has 3 attributes.
I implemented this interface in my class as follows:
public class MyCar implements MotionListener {
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("widnowIsOpened" + velocity.widnowIsOpened());
/*
I need here to set up a listener for the boolean value widnowIsOpened
because this boolean may be change later and this method will not be invoked again
, it is just invoked once but
value of windowIsOpened may change by the library
*/
}
#Override
public void onObjectStopped() {
}
// other methods ...
}
What I need is to listen to the boolean value changes to react to the changes in my code. I did a lot of searching on this topic, but all possible solutions that i found if I have access to Velocity class so I can set listener inside the Velocity class,
but in my case I have only the passed object.
So the only thing I can do is to check if the
widnowIsOpened is true or false, but not for change.
Any help?
You can write your custom listener class with some method in that class. Call that method of listener class inside onObjectMoved() method based on the boolean value.
If you want to send update to multiple listeners, then write a interface for listener and writes its implementations.
If you want I can share some piece of code with you.
Here you go:
public class MyCar implements MotionListener {
private VelocityListener listener;
// added constructor
public MyCar(VelocityListener listener) {
this.listener = listener;
}
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("isMoving" + velocity.isMoving());
// added handling
listener.doSomething(velocity);
// I need here to set up a listener for the boolean value isMoving
}
#Override
public void onObjectStopped() {
}
public static void main(String[] args) {
MyCar car = new MyCar(new VelocityListenerImpl());
//if you are using java 8 then you can use functional interface like below
//MyCar otherCar = new MyCar(()->{System.out.println("velocity changed....");});
}
}
Listener and its implementation
public interface VelocityListener {
public void doSomething(Velocity velocity);}
public class VelocityListenerImpl implements VelocityListener {
public void doSomething(Velocity velocity) {
while (true) {
if (velocity.isMoving()) {
System.out.println("velocity changed....");
}
}
}}
is actually the oposite, the car need the interface but no need to implement it
public interface MotionListener {
void onObjectMoved(Velocity velocity);
void onObjectStopped();
}
public class MyCar {
private MotionListener myMotionListener;
private void setMotionListener(MotionListener someMotionListener){
myMotionListener= someMotionListener;
}
public void doSomething(){
if(myMotionListener != null){
myMotionListener.onObjectMoved(myVelocity);
}
}
public void notifiyamStop(){
if(myMotionListener != null){
myMotionListener.onObjectStopped();
}
}
// other methods ...
}
public class MyPolice implements MotionListener {
#Override
public void onObjectMoved(Velocity velocity) {
System.out.println("Distance" + velocity.getDistance());
System.out.println("Speed" + velocity.getSpeed());
System.out.println("isMoving" + velocity.isMoving());
// i need here to setup a listener for the boolean value isMoving
}
#Override
public void onObjectStopped() {
}
// other methods ...
}
Apparently, MotionListener is the listener. You need to implement it. Each time MyCar moves, the OnObjectMoved() and OnObjectStopped() methods are called. In those methods, do whatever needs to happen when the car moves or stops, such as recalculating the position.
As far as listeners, the listener will be called by the external entity each time the velocity changes. So, your method simply needs to look at the value and do something with it. I'm guessing Velocity has getters for speed and direction.

What is the usage of the IVisitable interface in Visitor Pattern?

Im really trying to understand the importance of this interface, but beside helping us to write more quickly, the methods in the concrete classes (by only implementing the methods) I just can't find the need to use it.
The definition is this
an abstraction which declares the accept operation. This is the
entry point which enables an object to be "visited" by the visitor
object.
Each object from a collection should implement this abstraction in
order to be able to be visited
."
Its clear, but still you can manualy write those accept methods in every single class(which is lot of unnecessary work I agree) but still beside that you can get a class to be visitable, without the IVisitable interface...
//IVisitable.java
package Visitor;
/**
*
* #author dragan
*/
public interface IVisitable {
public void accept (Visitor v);
}
// Bgirl.java
public class Bgirl implements IVisitable{
int _br_godina;
public Bgirl(int g) {
br_godina = g;
}
public int getBr_godina() {
return _br_godina;
}
public void accept (Visitor v){
v.visit(this);
}
}
// Main.java
package Visitor;
/**
*
* #author dragan
*/
public class Main {
public static void main(String[] args) {
Bgirl terra = new Bgirl(5);
System.out.println(terra.getBr_godina());
VisitorImplement v = new VisitorImplement();
}
}
// VisitorImplement.java
package Visitor;
/**
*
* #author dragan
*/
public class VisitorImplement implements Visitor{
#Override
public void visit(Bgirl prva) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
prva._br_godina = 3;
}
// #Override
// public void visit(Bboy prvi) {
// // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// System.out.println("BBOY VISIT");
//
// }
//
}
Look into your main() method: you can just directly call terra._br_godina = 3 and thus no need to use any visitor.
A visitor is useful when you don't know the concrete type of your terra and even don't know which method should be called to fullfil your wish. All you have is just an abstract type or interface e.g. Girl (or IVisitable). So, to demonstrate the usefulness of Visitor Pattern, your main() method should be like this:
public static void main(String[] args) {
IVisitable terra = new Bgirl(5);
// Want to set _br_godina of terra to 3 but do not and cannot know
// which method should be called
// Let's create a visitor and let him visit her,
// he knows how to set _br_godina of her to 3
VisitorImplement v = new VisitorImplement();
terra.accept(v); // luckily, every girl accepts the "accept()"
}

C# equivalent to implement interface inside super keyword in Java [duplicate]

I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :

Redirect method call at runtime to introduce some kind of sandbox

I'm in bit of a fix with this problem. Hoping for a silver bullet.
I have a few singletons(~10) which all have a few functions (~10 each). My function calls look like this (as they should). Note: Most of these calls are async and do not return anything. Only a handful are synchronous
SingletonClassGorrilla.getInstance().methodSwim(swimmingPool, lifeJacket, whistle);
SingletonClassRacoon.getInstance().methodBark(thief, owner);
I need to put all these calls in a sandbox:
Sandbox.runThisInSandboxMode(new Runnable{
#Override
public void run(){
SingletonClassGorrilla.getInstance().methodSwim(swimmingPool, lifeJacket, whistle);
}
});
As the number of places where they are being called is huge, I am hoping that the sandboxMode can be achieved at the Singleton end.
Possible solution (but infeasible because of the number of functions I will have to wrap like this):
public class SingletonClassGorrilla{
public void methodSwim(WaterBody waterBody, Instrument instrument,
EmResponse emResponse){
Sandbox.runThisInSandboxMode(new Runnable{
#Override
public void run(){
methodSwim(swimmingPool, lifeJacket, whistle, true);
}
});
}
private void methodSwim(WaterBody waterBody, Instrument instrument,
EmResponse emResponse, boolean fromSandbox){
// Do your thang.
}
}
Is there anyway, through use of reflection / annotations / any other thing in the language, which can reduce the amount of changes required?
You can use a Proxy with a suitable InvocationHandler (though you'd have to pull out an interface for each of your singletons). Disclaimer: I haven't tried to actually compile/run this code, but it should give you the general idea. If you care about return values from your singleton, you may have to use Callable instead of/in addition to Runnable in your sandbox interface.
public class SingletonGorilla implements GorillaInterface {
private static SingletonGorilla theRealGorilla;
public static GorillaInterface getInstance() {
//In reality, you'd want to store off the Proxy as well
return Proxy.newProxyInstance(SingletonGorilla.class.getClassLoader(), GorillaInterface.class, new SandboxingHandler());
}
private static class SandboxingHandler implements InvocationHandler () {
public Object invoke(Object proxy, Method method, Object[] args) {
return Sandbox.runInSandbox( new Runnable() {
public void run () {
method.invoke(proxy, args));
}
}
}
}
I'm thinking about something along the following lines:
First, you'll need an interface for each of your singletons:
Interface:
package org.test.proxywrapper;
public interface IGorilla {
public void methodSwim();
}
Implementing class:
package org.test.proxywrapper;
public class Gorilla implements IGorilla{
public void methodSwim()
{
}
}
Then, implement an InvocationHandler that factorize the code that will be common to each call to the methods of Gorilla:
package org.test.proxywrapper;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class WrapperInvocationHandler implements InvocationHandler {
#Override
public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
Sandbox.runThisInSandboxMode(new Runnable() {
#Override
public void run() {
Object params = new Object[0];
try {
arg1.invoke(arg0, new Object[]{});
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
});
// return something if you need to
return new Object();
}
}
At this point, in a central place in your application/system, wrap each singleton with a Proxy, and pass the proxy reference around instead of the original wrapped object:
package org.test.proxywrapper;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String argv[])
{
WrapperInvocationHandler wrapperInvocationHandler = new WrapperInvocationHandler();
Class<?>[] implementedTypes = new Class<?>[1];
implementedTypes[0] = IGorilla.class;
IGorilla proxy = (IGorilla) Proxy.newProxyInstance(Main.class.getClassLoader(), implementedTypes, wrapperInvocationHandler);
proxy.methodSwim();
}
}
This simple example compiles and runs as I would expect.
I cut some corners here, skipped the getInstance method, etc, but I guess it gives an idea of how it can be done.

Java - Calling a public method (not public void)

I have this code but I am unsure how to call the public create() method with the public static void main(String[] args) method in a different class. I have searched the net but found nothing on just public methods just public void methods.
Here is the code
mainclass.java:
public class Mainclass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
create createObject = new create();
createObject.create();
System.out.println("dammit");
}
}
create.java
public class Create extends javax.swing.JPanel {
public create() {
initComponents();
setDate();
}
}
That is actually a constructor. You call it with new.
create panel = new create();
Having a class with a lowercase name is highly unorthodox.
That is a constructor, not a normal method. You can see that it has the same name as the class it's in. It's called here:
create createObject = new create();
BTW, calling a class create makes me a sad panda.
public create() {
initComponents();
setDate();
}
create() Is a constructor so when you say Create createObject = new Create(); the without parametrized constructor will automatically call.
read here for constructor
and please follow the java naming conventions class name always start with caps letter.
Starting with something Off-topic but you might want to read about the Java Naming Convention to understand how to name your classes/methods/variables in Java.
Constructors as we know have declarations that look like method declarations—except that they use the name of the class and have no return type. So you can have something like this:
public class create extends javax.swing.JPanel {
/** Normal Constructor */
public create() {
}
/**
* Normal method for initialization.
*/
public void create(){
initComponents();
setDate();
}
}
I tend to prefer having a specific method to handle object initialization (or setup, if you may) for my classes i.e. kept all business logic separate from object creation mechanism. So, if I were you, I would've renamed my method as public void doCreate() and initialized everything over there. (This is subjective and a matter of preference). With this case, my MainClass would have changed something like this:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
create createObject = new create();
createObject.doCreate();
System.out.println("dammit");
}
}

Categories