Java reflection: How can I retrieve anonymous inner classes? - java

I have an anonymous inner class inside another class (SomeClass).
Both SomeClass.class.getClasses() and SomeClass.class.getDeclaredClasses() return empty arrays.
I couldn't find some hints on this in Class' Javadocs.
Can anonymous inner classes be retrieved using reflection in some way?
What else are notable differences between anonymous inner classes and normal inner classes?

You could try a brute force search of Class$1 ... Class$n until you can't find any more.

If it's using reflection, it's probably a really bad idea. Leaving that aside, I believe you can additional inner classes at runtime, so it doesn't make sense to list classes that may not have been thought of yet. Listing currently loaded classes would, I guess, require going through Java agents or similar.
Anonymous inner classes have made up names, an enclosing method and additional synthetic fields for copying external local variables that have been copied. One class is pretty much the same as another at runtime. Remember that 1.1 introduced inner classes, but class files have barely changed since 1.0.

Related

How Anonymous class different from other classes in Java?

I know that Anonymous class does'nt have any name.
It is used inside the Simple classes.But more than this,how Anonymous classes are different from Simple classes we use?
Anonymous classes are the same as local classes except they don't have a name.
They are expressions not declarations. So it will be part of a staement (i.e. the statement which creates the object and so we are placing a semicolumn after an anonymous class definition). You can use an anonymous class if you need to use it only once.
Major points:
You cannot declare a constructor inside it.
Can access all class level variables of the enclosing class and only final local variables.
Cannot declare static initializers, but can have static variables which are declared as final also.
In Java 8 lambdas are having similar syntax to anonymous classes and they can replace anonymous classes if you need a stateless implementation.
They are mostly used in UI programs to handle events. If your class/interface does a little functionality then instead of creating new file for it you embed it in the existing class. You can find elaborate description on https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html.

Is it mandatory utility class should be final and private constructor?

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object

Java: Should serializable inner & anonymous classes have SerialVersionUID?

Although I'm not currently planning to serialize anything, I give all serializable outer classes, as well as static nested classes a SerialVersionUID, because that is the proper way to do it.
However, I've read here that
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged for several reasons. ...
So my question is:
Should I give inner and anonymous classes a SerialVersionUID each, or should I add a #SuppressWarnings("serial") to those?
Is one way more proper than the other?
I will in any case make references to such classes transient, because I don't want them to be serialized.
Give them a serialVersionUID, because:
It's good general practice and it certainly doesn't hurt to specify it.
Warnings should be addressed, not suppressed.
Sometimes inner classes are changed to be top-level classes when they get large enough.
It's good (for all of the reasons stated in the documentation to which you've linked) that you won't be serializing instances of those inner classes. I suppose, if you were paranoid or worried other developers might not exercise the same good judgement, you could enforce that choice by having a writeObject method in each inner class that unconditionally throws an exception.

Limitation of anonymous classes in java?

I have been facing so many problem using the anonymous class like I can't perform the instanceOf test neither can I implements multiple interface, so could someone please explain what I can or can not do with the anonymous class in java ?
The purpose of an anonymous inner class is to extend and instantiate an existing class or implement a single interface in one step.
Its limitations can be derived from the above:
Only one non-final class can be extended or one interface implemented.
Only final local variables of the enclosing method can be accessed. (This is due to the fact that normal local variables will be out of scope by the time any methods of the inner class will be invoked.)
You can't define a constructor. (The class has no name.)
If you need multiple interfaces, you can use a local inner class, which is like a normal inner class, with its own name, but defined within a method. I have to admit I've never seen it used in practice and I see very little reason for anyone to do so, hopefully someone will come up with an example.
Anonymous classes work whenever
you never need to refer to the class itself
you only need to extend a single class or implement a single interface
...but other than that there aren't really any significant constraints. This works fine in a lot of cases: for example, many cases when you're defining callbacks, listeners, or the like.

Java: Subclass access without package access

Fairly new to Java, but I'm wondering why package access is considered "more restrictive" than subclass access. That is, every access modifier which provides subclasses with access to a member also provides the whole package with access, and there are modifiers whic provide package access but not subclass access.
Isn't this totally backwards? Let's say I have a class ControlledInstantiation in some package. If I have another class AlsoControlledInstantiation extends ControlledInstantiation, I am unable to call the constructor of ControlledInstantiation unless I set it to protected or public. And if I set it to protected, now any other class in the package can instantiate it as often as it likes. So something which is obliged to be substitutable for its superclass (and, syntactically, is) gets the same or less access to the superclass than something which serves a distinct but related function. It's like telling your child he can't play with your wallet because you wouldn't let your neighbours do it and then letting your neighbours sleep in your house because your kid does.
So I guess I'm asking, what motivated this decision, and how can I get around it?
It may seem backwards at first, but the idea is that a Java package should contain a set of comparatively cohesive classes which are semantically related, and this is reflected in the default package modifier. Then the logic is that if you want to go one step further and allow subclasses from any package to view your members, you can declare them protected. Does it make sense to you that subclasses from foreign packages should be less trusted than any class (whether a subclass or not) from your own package?
Java did in fact once have a private protected modifier which would achieve what you're after, but it was removed, I imagine, because it confused people. I'm not really sure how you could achieve this without relegating each class/subclass pair to its own package. But that's a messy solution which goes against Java's principles and it wouldn't work for inheritance hierarchies of more than two classes anyway.
You are right, this fact is a little bit confusing.
Here are the workarounds I can suggest.
Your example with protected constructor is more relevant for methods. In some cases you can avoid access to protected constructor by package member that are not the subclasses of current class if you mark class as abstract.
If you really wish to avoid access to protected method by package members you can solve this problem at least at runtime using Throwable.getStacktrace():
if(!getClass().isAssignableFrom(
Class.forName(new Throwable().getStackTrace()[1].getClassName()))) {
throw new IllegalAccessException(
"This method can be accessed by subclass only");
}
You can seal a package. See the JAR File Specification.

Categories

Resources