Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an anonymous class while using reflection?

I would like to be able to implement a method at runtime that is called before an object runs the initializers. This will allow me to set fields that are used during initialization.

Here is an example:

class A {
  public A() {
    initialize();
  }
  public void initialize() { }
}

class B extends A {
  public String message;
  {
    System.out.println(message);
  }
}

public class MainClass {
  public static void main(final String[] args) throws Exception {

    Class<A> aClass = (Class<A>)Class.forName(args[0]);
    // what's next in order to something like this even though
    // I don't know what subclass of A was passed in as an
    // argument above 
    A a = aClass.newInstance()
    {
      public void initialize() {
        this.message = args[1];
      }
    };
  }
}

I will probably end up using aspects, but I would like to know if there is a pure Java way.

like image 862
Matt Avatar asked Feb 24 '11 03:02

Matt


People also ask

Can anonymous class be created?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Can we create anonymous class with interface?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.

Can we use anonymous class for abstract class?

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).

How do you access private class using reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.


1 Answers

Do you mean something like this assuming it would compile (which it doesn't):

@Override
A a = aClass.newInstance()
{
  public void initialize() {
        this.message = args[1];
      }
};
like image 127
user207421 Avatar answered Dec 20 '22 12:12

user207421