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.
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.
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.
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).
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.
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];
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With