Why are hashCode() and getClass() native methods? - java

I checked the source code of Object class where I found that method declaration of getClass() was
public final native Class<?> getClass();
And the declaration of hashCode() was
public native int hashCode();
Why are these two methods native methods in the class and how can I get the source code of those methods?

You can find the complete source code of the native methods here
I hope this will work for you.
These are native methods, because it has to interact with the machine. Here machine dependent code is written in the C language, which is not coming with the source package or in rt.jar of the lib location of the Java Runtime Environment (JRE).
One more reason for being native is possibly for the performance reasons. Due to the C level programming performance may be improved, hence they may have written the native code in the C language.
The methods are native because they concern native data. The hashCode method returns an integer value dependent on the internal representation of a pointer to an object on the heap. The getClass method must access the internal vtbl (virtual function table) that represents the compiled program's class hierarchy. Neither of these is possible with core Java.

Source code for Object class can be found here
This source contains implementation of getClass() method (See line 58). hashCode is defined as a function pointer JVM_IHashCode (See line 43).
JVM_IHashCode is defined in jvm.cpp. See code starting from line 504. This in turn calls ObjectSynchronizer::FastHashCode which is defined in synchronizer.cpp. See implementation of FastHashCode at line 576 and get_next_hash at line 530.
Probably, the methods are native for performance and due to practical issues w.r.t implementation.
For e.g., From javadocs, hashCode is typically implemented "by converting the internal address of the object into an integer". This internal address is not available via java sdk and will have to be implemented as a native method.
Please read Is it possible to find the source for a Java native method?. Also read this blog post Object.hashCode implementation. It gives more details. But makes a wrong assertion that hashCode is not generated from object's identity.
Hope it helps.

The information for these is in the header (for the class) or elsewhere (for the hashCode) This is not something you can implement in Java. The source for these methods is in the source for the JVM. e.g. you can download the source for OpenJDK.

Related

Kotlin object creation and memory management compared to Java

I've heard that in Kotlin creation of the new objects is cheap. How is Kotlin memory aspect of object creation is different from Java? Is there difference in cost of creating objects from the data class and class?
I think you mean Kotlin targeting JVM, so I will tell you about this target.
Kotlin uses the same bytecode as Java, so performance in general is the same (some operations can be less or more optimized in Kotlin(thanks to compiler or stdlib) in compare to Java).
Data classes are just normal classes with additionally generated toString(), equals(), hashCode() and clone() methods, so they have the same performance as normal classes.
I would expect no difference if Java and Kotlin are both compiled for same target VM - it should make no difference which source code produces the same bytecode.
As for data class, Hiosdra correctly pointed out that this is just a syntax sugar to tell the compiler to derive some standard methods useful for data-holding classes (see the documentation).

How to detect java local variables by an interface type and then find methods called on them?

I have some (maybe) strange requirements - I wanted to detect definitions of local (method) variables of a given interface name. When finding such a variable I would like to detect which methods (set/get*) will be called on this variable.
I tried Javassist without luck, and now I have a deeper look into ASM, but not sure if it is possible what I wanted.
The reason for this is that I like to generated a dependency graph with GraphViz of beans that depend on the same data structure.
If this thing is possible could somebody please give me a hint on how it could be done? Maybe there are other Frameworks that could do?
01.09.2015
To make things more clear:
The interface is self written - the target of the whole action is to create a dependency graph in the first step automatically - later on a graphical editor should be implemented that is based on the dependencies.
I wonder how FindBugs/PMD work, because they also use the byte code and detect for example null pointer calls (variable not initialized and method will be called on it). So I thought that I could implement my idea in the same way. The whole code is Spring based - maybe this opens another solution to the point? Last but not least I could work on a source-jar?
While thinging about the problem - would it be possible via ASM/javassist to detect all available methods from the interface and find calls to them in the other classes?
I’m afraid, what you want to do is not possible. In compiled Java code, there are no local variables in the form you have in the source code. Methods use stack frames which have memory reserved for local variables, which is addressed by a numerical index. The type is implied by what instructions write to it and may change throughout the method’s code as the memory may get reused for different variables having a disjunct scope. The names on the other hand are completely irrelevant.
When bytecode gets verified, the effect of all instructions to the stack frame will get modeled to infer the type of each stack frame slot at each point of the execution so that the validity of all operations can be checked. Starting with class file version 50, there will be StackMapTable attributes aiding the process by containing explicit type information, but only for code with branches. For sequential code, the type of variables still has to be derived by inference.
These inferred types are not necessarily the declared types. E.g., on the byte code level, there will be no difference between
CharSequence cs="foo";
cs.charAt(0);
and
String s="foo";
((CharSequence)s).charAt(0);
In both cases, there will be a storage of a String constant into a local variable followed by the invocation of an interface method. The inferred type will be String in both cases and the invocation of a CharSequence method considered valid as String implements CharSequence.
This disproves the idea of detecting that there is a local variable declared using the CharSequence (interface) type, as the actual declared type is irrelevant and not stored in the regular byte code.
There are, however, debugging attributes containing information about the local variables, see the LocalVariableTable attribute and libraries like ASM will tell you about the declarations if such information is present. But you can’t rely on these optional information. E.g. Oracle’s JRE libraries are by default shipped without them.
I don't sure I understood exacly what you want but .
you can use implement on each object ,
evry object that have getter you can implement it with class called getable .
and then you could do stuff only on object that have the function that you implement from the class getable .
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

How is Reflection Implemented in Java?

The Java 7 Language Specifications say pretty early on:
"this specification does not describe reflection in any detail."
I'm wondering just that: how is Reflection implemented in Java?
I'm not asking how it's used, and I understand there might not be as specific an answer I'm looking for, but any information would be much appreciated.
I've found this on Stackoverflow, the analogous question about C#: How is reflection implemented in C#?
The main entry point of any Reflection activity is the Class class. From it you can get Method, Field, Class, Constructor, and Annotation instances.
If you look at the source code, you will notice that to retrieve any of the above, Java has to make a native call. For example,
private native Field[] getDeclaredFields0(boolean publicOnly);
private native Method[] getDeclaredMethods0(boolean publicOnly);
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
private native Class<?>[] getDeclaredClasses0();
private native byte[] getRawAnnotations(); // get converted to Annotation instances later
The implementation is done in native C code (and/or C++). Each JDK might differ, but you can look up the source code if it's available and you have patience. Details on the OpenJDK source code can be found in this question.

clone () implementation in Object class

I was reading this article and it says that
Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor".
All I see in the grep code is the following line :
protected native Object clone() throws CloneNotSupportedException;
What am I missing here ?
You're missing the native which means it's implemented in non-Java code (in this case it's implemented in the JVM itself).
That's because the exact functionality of clone can not be implemented in Java code (which makes it so problematic).
The native keyword indicates that the implementation is in native (non-Java) code.
First of all, to actually understand the concept behind clone better I recommend the answer to the question: How to properly override clone method?
Regarding the source code you have put into your question:
native means here, that this is a method which is not implemented with Java, but with another language, often C or C++. It's still part of the JVM, hence you can find the actual implementation in the OpenJDK™ Source Release in the
"openjdk/hotspot/src/share/vm/prims/jvm.cpp":539
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
const KlassHandle klass (THREAD, obj->klass());
JvmtiVMObjectAllocEventCollector oam;
.
.
.
JVM_END
The method is marked as native, so you cannot see its implementation because it is not in Java.

Memory management using directors in SWIG C++ / Java

I am trying to create a Java wrapper for my C++ library using SWIG.
In order to get all the features I need within a Java programming environment, I need directors.
More specifically, I need Java users to be able to inherit from my C++ classes and implement certain methods.
In particular, one of the method that needs to be implemented is some sort of clone() method.
In C++, the user implementation provides an object pointer Base*. This pointer is then managed by the library itself.
Base* Derived::clone() {
return new Derived(*this);
}
The problem I have with the Java wrapper is that the Java proxy class for Base acquires the management of the corresponding C++ director class SwigDirector_Base, by default.
This is certainly suitable in the general case, but not in this particular user-defined clone() function.
My personal constraint is that the Java wrapper for my C++ library uses no Java-specific code, so the user implementation should look like:
class Derived {
...
Base clone() {
return new Derived(this);
}
}
So far, to make it work and avoid garbage collection of the copied Java instance, I have used the trick mentioned in http://www.swig.org/Doc2.0/SWIGDocumentation.html#CSharp_memory_management_member_variables.
And to make sure that the Java Derived class never deletes the corresponding C++ director class SwigDirector_Base, I have used %typemap(directorout) to set the value of the Java cMemOwn flag of the copied instance from the C++ wrapper code, that is in method SwigDirector_Base::clone().
I am not so happy with this solution as it applies to all methods returning a pointer to the Base class, whether it is a copy method or not...
Any idea on how to do this on a function-specific way? Or in any other way?

Categories

Resources