2

I have a private abstract class as a listener. I can access to it only reflected. How do I implement that class?

public class A {

    private abstract class OnWorkListener {
        public abstract void onWork(int param);
    }

    private OnWorkListener mListener;

    public A(OnWorkListener listener) {
        mListener = listener;
    }

    public void work() {
        // some working
        if(mListener != null) {
            mListener.onWork(0);
        }
    }
}



public class B {

    private static final String TAG = B.class.getSimpleName();

    public B() {
                //How to overwrite it?
        WorkListener listener = new WorkListener() {
            public void onWork(int what) {
                Log.d(TAG, "onWork "+what);
            }
        };
        A a = new A(listener);
        a.work();
    }
}

The problem is that I can't create an instance of the abstract class. I need to implement it first. But I can't find an answer.

GraphicsMuncher
  • 4,583
  • 4
  • 35
  • 50
melnik
  • 55
  • 6

3 Answers3

4

There is no way to implement classes or interfaces with reflection - in a certain sense, reflection is "read-only", letting you examine and manipulate what's already there.

You need to emit Java code in order to build an implementation at run-time. There are several options available for that - check out this answer for some very good references.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

There are actually two errors in one: - A.WorkListener is not visible from B (because it is private) - A.WorkListener needs an "enclosing instance" of A (because it is not static)

Since the constructor of A is public, it makes sense to declare WorkListener as public too. (but package visibility would work too, provided that A and B are in the same package).

public class A {

    public abstract class WorkListener {
        public abstract void onWork(int param);
    }
...
}
Javier
  • 12,100
  • 5
  • 46
  • 57
0

You are trying to implement in class B a private class located within class A. Class B can´t see that class whatsoever, it´s like trying to access a private attribute from outside the class.

If your question referes to the implementation and why B can´t see it, just refactor class A and do "Move inner to outer level", which means make your private class a class just like A or B,. Another option is to make it public.

Chayemor
  • 3,577
  • 4
  • 31
  • 54