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.
Related
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?
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.
I'm going to write my own Python-Java interface. It is compiled as a DLL and
wrapped using ctypes.
Yet, it is possible to find Java-classes and allocate Java-objects.
But what would be an interface to another language without using those objects
methods? My aim is to make this as natural as possible. Unfortunately,
it isn't just possible to find Java-methods only by name.
My model is the following:
JClass
An instance of this class represents a Java class.
JObject
An instance of this class represents a Java-object. It has to be
initialized with a JClass-instance. (yet, of course, later there
should be arguments for the constructor also.)
JMethod
Represents a method of a Java-object. It contains the name and signature of the desired method. The signature is evaluated dynamically by the classes that are given on initialization.
Example:
mainMethod = JMethod('main', JStringArray)
Note that JStringArray is an instance of JClass that represents a string-array.
A JMethod can be added to a JClass instance. But can then be called only from an instantiated JObject.
JStaticMethod
Just like the JMethod, but it can also be called from a JClass
instance.
Built-In types
I'm doing JInt, JShort, JLont, JChar, etc.. to be the
built-in wrapper types.
Like:
JInt = JClass('java/lang/Integer')
JShort = JClass('java/lang/Short')
JString = JClass('java/lang/String')
Question(s):
What do you think about this design?
The JNI-Functions for calling methods of a Java-class / -object all
take a variable amount of arguments. After reading several topics on
calling a function with variable arguments from a function that does so,
and also asked a question here on SO, I'm aware that this is not possible.
Now, are there functions that don't take a variable number of arguments
but a va_list or something? I just need to find some way to call a method from Python in Java!
1. What do I think of this design?
it's not clear what actual problem you're trying to solve.
what about edge cases; error-handling; forward-/backward-compatibility; bugs in Python/Java? Not fun, but essential for robust software.
mixing two languages is hard enough, mixing three is sure to be much much worse. I would expect major maintainability and coupling problems.
there are already solutions to these problems. RPC, for getting programs in different languages to talk to each other. Jython, for Java/Python interoperability. I believe, Jython even allows you to create Python objects in Java and vice versa directly. Clarifying any shortcomings of these existing systems, and how you would address these shortcomings, would be helpful.
Here are a few missing things:
packages
privacy
interfaces/abstract classes
method resolution: overloads and overrides(especially when more than one method would match)
exceptions
type-checking, or recovering from type errors
2. I just need to find some way to call a method from Python in Java! What about Jython, RPC, or just calling an executable?
How to declare and call a native method in c containing pointers using java?
please it is urgent.Because there is no concept of pointers in java i am getting error.
Use JNI(Java Native Interfaces) to call native methods in java. Use this JNI specification pdf as a reference "java.sun.com/docs/books/jni/download/jni.pdf".
There is even a easier approach to the subject, if you or your boss are willing to pay 50$!
Is called eXcelsior xFunction. Try the evaluation version.
Works very well and is simple to use.
The only thing xFunction library does not do have is implementation of address arithmetic in Java, which i assume you will possibly never need.
From their site:
With xFunction, you no longer need to implement those ugly native methods. Instead, you extend and instantiate xFunction classes to create conventional Java objects representing external functions, data structures, pointers, and callbacks. All necessary data conversions and external function calls are done seamlessly by the xFunction library:
import com.excelsior.xFunction.*;
...
/* Call Beep() from KERNEL32.DLL */
xFunction f =
new xFunction( "kernel32",
"int Beep(int,int)" );
f.invoke( new Argument(1770),
new Argument(100) );
I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.