How jvm classloader loads class that is defined inside another class? - jvm

How does JVM loads class that are defined inside another class?
Example: Lets say, there is a class B that is defined inside class A
package test.sample;
Class A {
// some instructions
Class B {
// few more instructions
}
}
In this case,
How does classloader load the class B? (i.e., How does it identify class B?)
What will be the fully qualified name of class B?

Inner classes are a Java language feature, not a JVM feature. That is, Java compilers "flatten" the class structure, so the JVM just sees regular classes, usually with $ in their names. In this case, there would be classes test.sample.A and test.sample.A$B (the latter being the fully qualified name of B). Anonymous inner classes get compiler-defined names, typically starting at 1 and counting up: test.sample.A$6, for example. The compiler may add methods with names like access$200 to allow the enclosing class and inner class to access each others' private members. (Note that $ is legal, though discouraged, in user-defined class and method names, so the presence of a $ in a name does not mean it is compiler-generated; for that, there's the Synthetic attribute and ACC_SYNTHETIC modifier bit, exposed reflectively via methods like Class.isSynthetic().)
The JVM loads these classes just like any other class, typically looking for a file test/sample/A$B.class in some JAR file, but also possibly loading them across a network, generating them on-the-fly with a bytecode manipulation library, etc.
When generating class files that reference an inner class (defining, containing, or simply using), Java compilers emit InnerClasses attributes specifying the containment relationships, for the aid of separate compilation and reflection (Class.getDeclaringClass() and Class.getEnclosingClass()). Class files for classes defined inside a method also contain an EnclosingMethod attribute referring to the enclosing method, for reflection (Class.getEnclosingMethod() and Class.getEnclosingConstructor()). However, these attributes are only checked for syntactic well-formedness by the JVM during loading and linking; inconsistencies are not reported until the reflective methods are actually called.

Related

What is the difference between sealed and internal in Kotlin?

What is the difference between sealed and internal in Kotlin? I have read Kotlin's documentation on sealed classes and visibility modifiers; however, it is still not clear to me when to use sealed vs. internal. Maybe someone could provide real-world code samples?
Sealed classes | Kotlin & Visibility modifiers | Kotlin resources.
sealed class will be visible in all modules, but extendable only in the same module. This means if you have this:
sealed class MyClass {} then you can do this in the same module:
class MyExtensionClass: MyClass() {}
But you can't do the same thing in another module. But you can still use both MyClass and MyExtensionClass in another module.
For example you can do this in another module:
val x: MyClass = MyExtensionClass()
You can't instantiate a sealed class directly neither in the same or another module. This means you can't do this nowhere:
val x = MyClass()
So sealed class is basically an abstract class which can only be implemented in the same module.
internal class can be used and extended in the same module just like a sealed class, but you can do neither in another module. So you can't even use or instantiate it in another module. Also you can directly instantiate an internal class as long as you are doing it in the same module.
So: Use sealed to better control extending something. For example you create a library and you want a class from this library to be used but not extended. Use internal if you wan't your class to be invisible to other modules (you create a library, but certain class in this library shouldn't even be directly compile time usable by libraries users)
A good use case for sealed class:
You build a library and have some abstract class or interface which has multiple different implementations, but you want to make sure the libraries user doesn't add its own implementations (you wan't to be in control of implementation details).
A good use case for internal class:
You have some interface and a factory that creates implementations, but you don't want the implementing class to be compile-time visible to libraries users. They just use the factory and don't need to worry about the implementation. They might build their own implementation though and therefor not use the factory you provided and this is OK.
These are not mutually exclusive. You can have an internal sealed class as well.
internal is about visibility, and sealed is about inheritance rules.
internal means the class type is only visible within the module. In other modules, you can't even mention the name of the type.
sealed means it is open (can be subclassed), but subclasses (or implementations if it's a sealed interface) can only be defined in the same module, and the compiler keeps track of an exhaustive list of all subclasses. Another rule is that you can't create anonymous subclasses of it (object: MySealedClass). The advantage of a sealed type is that the compiler knows when you've exhaustively checked a type in when statements, if/else chains, etc. It can also be used in a library to ensure that only known implementations of a class or interface are ever passed to it (prevent users from creating subclasses of something and passing them into the library).
Bonus:
Visibility modifier keywords: public, internal, private, protected
Inheritance modifier keywords: open, final, sealed
data and value also cause a class to be final implicitly as a side effect.

How to get only declared members (not inherited) with Kotlin Reflection?

Is there any way to get only the declared members of a class (not inherited) with Kotlin Reflection?
Something equivalent to getDeclaredMethods(), or ...Fields(), in Java, but for members and JVM free, which:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
Or like a binding flag, such as BindingFlags.DeclaredOnly of dotnet.
Because the reflection is based on the class, So the following is only for the kotlin/JVM, not suitable for the Kotlin/JS or Kotlin/Native.
For the Kotlin/JS it supports limit, for detail, you can see this
document
The only supported parts of the API are: (::class),KType and typeOf
Firstly, you can use the SomeClass::class.java.declaredMethods to get the
getDeclaredMethods. That is the java method. Because the Kotlin file after compiled it is still a class. so you can directly use it.
You can also add the kotlin reflect to get the KClass, then use the declaredFunctions to get. Here is the Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
For how to get the KClass, you can use the following code
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
Besides the method, the other property you can also get. such as
declaredMembers
Returns all functions and properties declared in this class. Does
not include members declared in supertypes.
allSuperclasses
functions
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
you can read the document using it.

Why does ABAP divide classes into implementation and definition?

I know that ABAP Objects are kinda old but as far as my knowledge goes you still have to use at least two "sections" to create a complete class.
ABAP:
CLASS CL_MYCLASS DEFINITION.
PUBLIC SECTION.
...
PROTECTED SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
CLASS CL_MYCLASS IMPLEMENTATION.
...
ENDCLASS.
Java:
public class MyClass {
<visibility> <definition> {
<implementation>
}
}
Wouldn't it make development easier/faster by having a combination of both like most modern languages have?
What are the reasons for this separation?
Easier/faster for the human (maybe), but costly for the compiler: It has to sift through the entire code to determine the structure of the class and its members, whereas in the current form, it only needs to compile the definition to determine whether a reference is valid. ABAP is not the only language that separates definition from implementation: Pascal did so for units, and Object Pascal for classes. One might argue that C++ allows for same construct without specifying an implementation section when you're not using inline member function declarations.
Maybe another reason:
Most (?) classes are not defined with manual written code, but via SE24. There you define the interface in one dynpro and write the code in another one.
Internally the interfaces are stored in one source, the code is stored in another source. So it is reasonable to separate the interface and the implementation.

Can't create private classes with same name in different modules

Official docs on visibility modifiers in Kotlin say that package-level elements marked private are be visible only in the module in which they are declared.
So class A declared in Module1.kt isn't visible in Module2.kt. But if I try to add to Module2.kt it's own class A I get the Redeclaration: A error.
Since I can't access in Module2.kt to Module1's A class, why isn't the name A free to use?
"A module is a set of Kotlin files compiled together" (Visibility Modifiers - Kotlin Programming Language).
In your example, Module1.kt and Module2.kt are separate source files and despite their names they are not necessarily part of separate modules:
If they are compiled together then they are part of the same module.
If they are compiled separately from one another then they will be part of different modules and each can define their own private class A.
Keep in mind that visibility is different from identity. Even if a class is not visible elsewhere it doesn't mean that it does not exist. Loading multiple class declarations with the same fully-qualified name can (and likely will) cause issues at run-time.

When should we create a static class?

How can we distinguish to create a class which is static?
A static class forces all of its methods to be static and prohibits an instance constructor therefor can't be instantiated. If your question extends to WHEN to use static and WHEN instance, please do a search on StackOverflow (or check out the Related box on this page)
At least in C#,
static classes and class members are used to create data and functions that can be accessed without creating an instance of the class.
If you want the class to be static in nature i.e. have only 1 copy within the program (VM) then there are two obvious mechanisms:
1. Make all members and methods of the class static (Java/C#).
2. Use Singleton design pattern.
For this case (static in nature), we don't have a language construct and hence one of the above technique is used.
As to your question for this case, such classes should be created if you want your functionality to be accessible globally, unchanged and instantly accessible e.g. utility methods, global constants etc.
Secondly, the keyword 'static' is used with classes to increase their visibility in the package. This keyword can only be applied on inner classes and allows the access to inner classes without the context of their parent class.
Such kind of static classes should be used only for those inner classes that serve their purpose within the parent class as well as are useful outside the class or the package e.g. Key of a POJO.