Java: call a class by ID - java

I have a class "Class1" which implements Observer and contains a thread like this:
class Class1 implements Observer {
String id = null;
Object lockObject = new Object();
public Class1(String id) {
this.id = id;
theThread.start();
}
public void update(Observable arg0, Object arg1) {
lockObject.notify();
}
Thread theThread = new Thread() {
public void run() {
while(true) {
lockObject.wait();
printID();
}
}
};
public void printID() {
System.out.println( /*the ID of this class*/ + " was called");
}
}
and another, "Class2" which extends Observable and calls the first class:
class Class2 extends Observable {
public Class2() {
addObserver("ID_THREAD_ONE"); //Though it takes a class as parameter
setChanged();
notifyObservers();
}
}
public class Main {
public static void main(String[]args) {
new Class1("ID_THREAD_ONE");
new Class2();
}
}
Of course the code wont work because the method addObserver() takes an object of a class as parameter (In this case the object of Class1).
But I wanted to know if there was a way to make the addObserver method add an Object of a class by a before defined "class-id".
I know it would be easier to just do it like: addObserver(new Class1()), but i cant for some reason (which is also why i need to use id's).
Any answers are appreciated and thanks in advance,
cheers,
Julien

You may want to specify why your ID's are necessary. If they're to be used for some sort of mapping I guess they could stay as is.
As for the actual Observer/Observable, since both your classes are instanciated from the Main class, I think this is what you're looking for:
In your Class2 you have to include a Class1 instance in your constructor.
class Class2 extends Observable {
public Class2(Class1 observer) {
addObserver(observer);
setChanged();
notifyObservers();
}
}
Then, in your Main, simply pass the Class1 instance in the Class2 constructor like this:
public class Main {
public static void main(String[] args) {
new Class2(new Class1("someID"));
}
}
"someID" is there just in case you'd need it for something else, but other than that, no need to use ID's in the Observer.

Related

C# vs JAVA instance of Interface

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 :

How to pass Object Context to a callback interface in Java

Trying to get a handle on "callback interface". The concept as I understand it make sense except for the following
//FromSomeClass1
MyInterface conect;
public void setInterface(MyInterface myInter)
{
this.conect=myInter;
}
interface MyInterface
{
public void update(String str);
}
(Fuzziness starts here)
So when another class attempts to
//FromSomeClass2 implements MyInterface
...onCreate()
{
SomeClass1 newC = new SomeClass1()
newC.setInterface(this) ;
}
update(String str){
....code
}
this will not work because I am passing to a new object ? Unless I make the "conect" variable in Class1 static (Good Idea bad Idea...consequences ???)
Simply what is the correct way to pass the object back to "setInterface" method .
Hope that made sense and Thank You.
p.s.
To all those who want a good understanding of call backs this link will help.
Consider an example Animal interface with a single says(String) callback,
interface Animal {
public void says(String msg);
}
Next, let's add a class that uses the Animal interface to say something -
class Say {
public void say(Animal animal) {
animal.says("Bawk");
}
}
Now let's implement two different Animal(s) - we're going to have a Cow class and a Sheep class,
class Cow implements Animal {
public void says(String msg) {
System.out.printf("%s, I mean moo!%n", msg);
}
}
class Sheep implements Animal {
public void says(String msg) {
System.out.printf("%s, I mean baah!%n", msg);
}
}
Finally, to demonstrate the callback method we defined above -
public static void main(String[] args) {
Say say = new Say();
say.say(new Cow());
say.say(new Sheep());
}
Output is
Bawk, I mean moo!
Bawk, I mean baah!
Is not that you need to make it static. I mean, you could make everything in SomeClass1 and make the client register by calling an static method SomeClass1.setInterface(this)
I won't recommend doing that tough. This is an example fallowing your code:
import java.util.HashSet;
import java.util.Set;
public class CallbackExample {
interface MyInterface {
public void update(String str);
}
static class SomeClass1 {
private Set<MyInterface> connects = new HashSet<MyInterface>();
public void register(MyInterface myInter) {
this.connects.add(myInter);
}
public void doWork(String someParam) {
for (MyInterface myInterface : connects) {
myInterface.update(someParam);
}
}
}
static class SomeClass2 implements MyInterface {
public void onCreate(SomeClass1 caller) {
caller.register(this);
}
#Override
public void update(String str) {
System.out.println("Doing some logic in update for " + str);
}
}
public static void main(String[] args) {
// Caller and callback creation are decoupled
SomeClass1 caller = new SomeClass1();
SomeClass2 callback = new SomeClass2();
// alternative 1. Preferred
caller.register(callback);
// alternative 2. Fallowing your example
callback.onCreate(caller);
caller.doWork("param1");
}
}
A good example of the use of callbacks is the android-async-http library. To make a HTTP request, you call a method and pass in the details of the request along with an object that implements a certain callback interface. The request method returns immediately, but after the request is complete, the library's worker thread sets up a call in the main thread to a method on the callback object you provided.

How to find instance of class which is calling method

I know about way how to find which class is calling my method, but this is not sufficient to my.
I have a problem that I have about 200 instances of same class(base class) and they have unique identifier which I can use for analysing problem.
Is there some way, how to find which instances called some method?
I know that debugger allow it, can I do it some how from a code?
You'd pass a reference for that instance to the method being called. For example, say you have two objects:
class ObjectA {
public void methodA() {
new ObjectB().methodB();
}
}
class ObjectB {
public void methodB() {
// How can I know who called me?
}
}
If MethodB needs to know which instance of ObjectA called it, then it would accept that information as a parameter:
class ObjectA {
public void methodA() {
new ObjectB().methodB(this);
}
}
class ObjectB {
public void methodB(ObjectA caller) {
// "caller" is who called me
}
}
There are lots of ways to tweak this. For example, maybe any given instance of ObjectB should have a reference to the ObjectA which created it:
class ObjectA {
public void methodA() {
new ObjectB(this).methodB();
}
}
class ObjectB {
private final ObjectA caller;
public ObjectB(ObjectA caller) {
this.caller = caller;
}
public void methodB() {
// "caller" called me
}
}
Or perhaps you don't want to couple the two objects together and want a more generic approach. You claim that the objects have some kind of identifier, what is that identifier? A String perhaps?
class ObjectA {
private String identifier;
// other code
public void methodA() {
new ObjectB().methodB(identifier);
}
}
class ObjectB {
public void methodB(String callerID) {
// "callerID" identifies who called me
}
}

How to substitute an abstract class with an interface in Java?

I have an abstract class Work with two abstract methods (init and work) and one concrete method (run) working with the abstract methods.
class work
{
abstract static class Work<T> implements Runnable
{
T data;
abstract protected void init ();
abstract protected void work ();
public void run ()
{
init();
work();
System.out.println (data);
}
}
public static void main (String[] args)
{
Runnable hello = new Work<String>() {
protected void init () { data = "Hello $1!"; }
protected void work () { data = data.replace ("$1", "World"); }
};
(new Thread(hello)).start();
}
}
In order to get rid of the multiple inheritance problem I would like to convert the abstract class into an interface. But in Java interfaces can not contain a body. So where do I have to put the generic data and method after converting the abstract class into an interface?
I fear that it is not possible to get rid of the multiple inheritance problem as long as I want to share anything concrete. Is this right?
You can do something like:
Create the Work interface
Create the AbstractWork class which is the abtract class implementing Work and containing the generic code
Create your implementation classes extending AbstractWork
That is exactly what is used in the JDK with List (the interface), AbtractList (the abstract class implementing List) and LinkedList and ArrayList (the implementation classes extending AbstractList).
You might have to separate the interface from the functionality; something like this:
public interface Work<T> {
void init();
T work();
}
public class Worker<T> implements Runnable {
private final Work<T> work;
Worker(Work<T> work) {
this.work = work;
}
public void run () {
work.init();
T data = work.work();
System.out.println(data);
}
}
public static void main (String[] args)
{
Runnable hello = new Worker<String>(new Work<String>() {
private String data;
public void init () { data = "Hello $1!"; }
public String work () { return data.replace ("$1", "World"); }
});
(new Thread(hello)).start();
}

Can a custom class know the name of the object that called it?

Is there anyway, when calling a method through an object (instance) for that method to know which instance (object) called it?
Here's an example (pseudo code) of what I mean:
Pseudo code example
public class CustomClass{
public void myMethod(){
if (calling method is object1){
//Do something here
}
else {
//Do something else
}
}//End of method
}//End of class
And then in another class:
public SomeOtherClass{
CustomClass = object1;
public void someOtherMethod(){
object1 = new CustomClass();
object1.myMethod(); //This will call the 1st condition as the calling object is object1, if it were some other object name, it would call the 2nd condition.
}//End of method
}//End of class
Possible work-around
The only way I've found to do this is to get the method to take another argument, say an 'int' and then check the value of that int and perform whichever part of the 'if else' statement relates to it (or 'switch' statement if definitely using an 'int' value) but that just seems a really messy way of doing it.
What you need is the Strategy Pattern
public abstract class CustomClass {
public abstract void MyMethod();
}
public class Impl1 extends CustomClass {
#Override
public void MyMethod() {
// Do something
}
}
public class Impl2 extends CustomClass {
#Override
public void MyMethod() {
// Do something else
}
}
Use it this way
public static void main(String[] args) {
CustomClass myObject = new Impl1();
// or CustomClass myObject = new Impl2();
}
As your comment says what you really need is perhaps the Template method Pattern
public abstract class CustomClass {
public void myMethod(){ // this is the template method
// The common things
theDifferentThings();
}
public abstract void theDifferentThings();
}
public class Impl1 extends CustomClass {
#Override
public void theDifferentThings() {
// Do something
}
}
public class Impl2 extends CustomClass {
#Override
public void theDifferentThings() {
// Do something else
}
}
You can know the name of current class by calling getClass().getName(). However you cannot know the name of object, moreover this does not have any meaning:
MyClass myObject1 = new MyClass();
MyClass myObject2 = myObject1;
myObject1.foo();
myObject2.foo();
Do you wutant foo() to know that it was invoked using myObject1 or myObject1? But both references refer to the same object!
OK, there are extremely complicated ways to know this. You can use byte code engineering using one of popular libraries like javassist, ASM, CGLib and inject missing information about the "object name" into byte code and then read this information. But IMHO this is not what you need.
You can define a new attribute inside CustomClass which will store the identifier of the instance. If there will be only a few instances of CustomClass then you can use an enum type.
Replace:
object1 = new CustomClass();
with:
object1 = new CustomClass(1);
Add a new constructor and an attribute to CustomClass:
private int id;
public CustomClass(int id) {
this.id = id;
}
Then you can replace:
if (calling method is object1){
with:
if (id == 1){
However, please keep in mind that this is a bad design.
You should not have if conditions differing logic depending on the instance which called this method. You should should use polymorphism for such purpose.

Categories

Resources