How to get address of a Java Object? [duplicate] - java

This question already has answers here:
Is there a way to get a reference address? [duplicate]
(5 answers)
Closed 8 years ago.
Is there a way to get address of a Java object?
Where the question comes from?:
At First, I read properties file and all the data from file was placed into table. Properties file can update. So, I want to listen that file. I listen an object using PropertyChangeSupport and PropertyChangeListener.
updatedStatus = new basit.data.MyString();
updatedStatus.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
//After changes "i", we inform the table model about new value
public void propertyChange(PropertyChangeEvent evt) {
Object objec=evt.getNewValue();
tableModel.setValueAt(objec.toString(), 0, 5);
}
});
If updatedStatus changes then i update table. MyString class have private String "Value". I want to listen properties file. So, it should make updatedStatus.value and String of Properties File equal at the same address. If i can do it, so i don't need to listen properties file.
updatedStatus.setValue(resourceMap.getString("HDI.Device.1.Name"));
I tried to use StringBuffer, but i couldn't achieve it. That's why, I asked the question.

Firstly - no, you can't get the address of an object in Java; at least, not pure Java with no debugging agent etc. The address can move over time, for one thing. You don't need it.
Secondly, it's slightly hard to follow your explanation but you certainly won't be able to get away without listening for changes to the file itself. Once you've loaded the file into a Properties object, any later changes to the file on disk won't be visible in that object unless you specifically reload it.
Basically you should listen for changes to the file (or poll it) and reload the file (either into a new Properties or overwriting the existing one) at that point. Quite whether you also need to listen for updates on the string container will depend on your application.

System.identityHashCode(obj) delivers the next-best thing: a number unique for each object. It corresponds to the default Object.hashCode() implementation.
To quote the API: "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)".

we can get address of an object in memory. Well how? it is like that;
using sun.misc.Unsafe class in java.
create new Unsafe object and use the getAddress(Object); method and it will return a long value that is address.
and also there are many methods for this class.
you can change the values in this address using putInt(Object,long offset, int value) or like this method.(getting some value getnt(Object)).
Note: this class is really UNSAFE . if you make wrong things on your project, JVM will be stopped.

Look into Apache Commons Configuration. This library has support for dynamic reloading of (for example) property files. See here.

The best way to observe if some file changes is IMHO to make a hash value with sha1 or mda5 and save the value in a cache. And you make a Thread that every minutes, seconds, depends how often you watch file changes, and make hash value over the file. So you can compare this two values and if the values are not equivalent so you can reload the new file.

Java not like C/C++. in C++, you will often work with address (that C++ programmer has a concept call pointer). But, I afraid that not in Java. Java is very safe that prevent you to touch its address.
But, there other ways maybe same with your idea is use HashCode. HashCode of an object base on their address on HEAP.

Related

Java serialization in memory instead of file

I learned about serialization in Java and how it can be done by saving object's generated byte code into file and then be deserialized back into an instance of the same class. But my question is can this be done without the files? Maybe to get a reference where is all that data stored in memory instead of file?
What I need is a history of an object's state (not just a reference to it) and to be able to bring this past state back at a later time. Thanks

Android: static variables and moving complex data

If I have a class that contains a static variable, say x:
class MyClass {
static boolean x = false;
// Other methods
}
Now let us say that, hypothetically, I set x = true; from my first activity. Is there any point through the rest of my app's life cycle (including various activities and threads) where this value will simple be 'reset' back to false due to how the 'Google JVM' or the android environment works? I have heard that static variables have a 'lifetime', that dies when the program dies. Do Activities count as separate 'programs'? What about services? Or even Widgets?
I am asking this because it is often difficult to share complex data structures that rely on other complex processing (like syncing data from an online database) in android due to how 'separated' activities are, and static variables are often a very quick and dirty solution to the problem. Other things I have tried include serialisation, but that doesn't really seem like a practical solution either (constantly serialising and decoding objects when the user navigates from one activity to the next seems like it would be very resource intensive).
If I am an evil person for doing this, please tell me what I am doing wrong, or even better, give me some links or examples of better ways to solve this problem.
Yes. There are times where that will reset. Primarily if the user leaves the app and starts fiddling around with other apps or if the user lets the phone go to sleep for a long period of time. The Android process could kill the actual app. Then the "state" of the app will be restored when the user comes back, however static variables will be at their defaults because the actual process was rebuilt.
Generally passing small objects between Activities and Services is done by overriding the Parcelable interface. This will allow you to save and restore objects using setOnInstanceState methods of both Activities, Views, and some adapters. They will likewise, have a restore method in which you can rebuild the object. Parcelable is preferable over Serializable.
Larger data may require a shared file or database depending on the data that you want to have synced. There is a 1 MB size limit for parcelables being passed between Activities. One common tactic is to save the information to a file and send a URI to the location of where the information can be retrieved.
Answering your question - yes, there is a situation when you set x = true and value will be 'reset' back to false. Well, not exactly reset but consider this scenario: you have an activity and a service. Service is using separate process (you can define that in AndroidManifest when you declare your service). Then those two processes (main app and service) won't share memory and setting x to true in your activity won't affect the value of MyClass.x in your service. In all other cases changing value in one place will be visible everywhere else. Hope it helps!
No, a static variable will not be changed unless you change it or the app ends, it is safe (but generally unclean) to use it. Closing the activity the variable lives in won't hurt it.
You suggest you just need to keep track of a value as you move around activities. In that case you can add the value in your Intents as what is called an 'extra'. If you need to also pass back the value after, android also has the startActivityForResult feature
Intent extras example:
x below could be any type of value including any object which implements Parcelable
Intent intent = new Intent(...);
intent.putExtra("myKey", x);
startActivity(intent);
in receiving class:
x = getIntent().getBooleanExtra("myKey");
Edit:
Given your additional comment - "lists of objects that contain yet more lists of objects" you may get a Parcel too large exception when trying to use extras, but this is an indication you have a bigger architectural problem and that there may be a better approach
Use Gson.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
You have two options. Convert to string , then put data in an intent then pass to activity. Or Convert to string with gson, save to a preference, then in the other activity, check if the preference is alive and read from it.
If you wish to be bold, you can persist to database preferably using Realm for Android or ObjectBox is a new mobile object database optimized for performance. With ObjectBox, we are bringing technology from NoSQL server databases to mobile.

The reference of the object changes in every debug

Doubtlessly, this question is asked already (may be many times) but I could not find the correct keywords to find them.
Basically, my question is about the object references. What I know is that the object references points the objects physical location on the memory. However, when I debug my code and every time when I debug, I get a difference object reference for the same object.
For example, when I firstly debugged my code and the reference of a button looks like
INFO [sysout] [AWT-EventQueue-0]
[Ljava.awt.event.ComponentListener;#28be012c
at the second time, it is
INFO [sysout] [AWT-EventQueue-0]
[Ljava.awt.event.ComponentListener;#31a056d8
My related questions are;
1.Is the part after (#) symbol (a.k.a #28be012c) reference to the object, if yes, it is something like ip address, which changes continiously?
2.Is there a way to obtain an address, which does not change over time (like a Mac-address)
Any answer or link related to these questions will be highly appreciated.
Edit
I am debugging in this scenario. There is a button and everytime when this button is clicked, the debugger stops at this point. That is to say, the program is not started from the beginning.
Is the part after (#) symbol (a.k.a #28be012c) reference to the object, if yes, it is something like ip address, which changes
continiously?
The part after the # is Integer.toHexString(hashCode());. The hashCodemethod is not designed to return the same value every time it is invoked for different runs (even if the object being created has the same value). It is also not mandatory that the returned value is related to the memory. JVM spec specifies that a unique value should be returned, but it doesn't specify "how".
Is there a way to obtain an address, which does not change over time
(like a Mac-adress)
No. Each run of the JVM will almost always give different hashcodes (unless you override the hashCode method to return something else.

Add new attribute to an existing file [duplicate]

This question already has an answer here:
Java - Properties: Add new keys to properties file in run time?
(1 answer)
Closed 7 years ago.
I am new in Programming. Let's get straight to the subject. I want to add a new attribute to a file using Java. For example, Every file has default attribute like Date modified, Date created etc. I want to add a new attribute to a file, say Rating.
Is it possible? then How can I do that ?
I've spend a lot of time in google, but nothing found helpful.
The existing attributes are defined and stored in the file system of the underlying operating system. Examples of file systems are NTFS and FAT32.
Some file systems allow for storing additional attributes for a given file, but it is rare, and even if you used one that did, you still need code either inside the runtime library or your own code which could talk to the underlying operating system to get and set the values you want to store.
At your current programming level, I would suggest looking into another solution to what you want to do this for. The typical way to save data is by talking to a database or - for smaller amounts of data - XML.

Monitor text file for changes in Java

I am trying to monitor a text file for a change in the one line of text it contains. The file is constantly being deleted and created with the same name and path but the content rarely changes.
I am trying to construct an if statement so that if the content of the file changes then the system will print to the console.
I have looked at this Stack Overflow question and tried using the java-diff-utils example found on this page, but I could not find a way to implement it to solve my problem.
Start by generating an MD5 of the original file, then using a background Thread, recalculate the MD5 and compare it with the original. When the hash changes, the file contents would have changed.
Check out MD5 Hashing Example
If you're using Java 7, you could use the Watcher Service to monitor changes to the file. This would replace the thread
"High-level" advice: you could...
Consume the file contents in a custom Object at app initialization, and store it in a static variable
Define a property for said object, returning a String which represents the contents of the file
Use a TimerTask to periodically instantiate a new instance of said custom Object representing the file, and...
... compare the two String properties, so that you can print out the
latter should they not be equal, and then overwrite the static variable's value with the newly instantiated object
Note that this is hardly the professional way to handle recurrent tasks or file comparison - it's just meant to give you a draft direction.

Categories

Resources