I have an object which after receiving some message changes state asynchronously (an internal thread changes the state). After the state changed I want to test some behavior.
So basically I need to do something like:
Create object
Send message to object
Wait for state to change
Test behavior
However, the state is private and not exposed.
Is there an elegant solution to this that does not require exposing the state?
And if not - is it reasonable to require changing the main code just to make it more testable?
if the state is private, it is only accessible within its own class (https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html) meaning that you will not be able to get the state from your newly created object without modifying the class.
Now, whether it is reasonable to modify the class in order to do some testing is up to several factors:
How many people working on that code?
How many people already using a previous version of that code?
Integrity issues that you would face if you change the state variable to public and add a getter method.
etc.
So of course I can't tell you if it is reasonable or not without knowing in detail the organization of your software.
I hope this short answer helps you at least to clarify the problem.
You can access the relevant private fields with Reflection assuming you have the permissions to do so.
Foo bar = new Foo();
bar.setValue(true);
Field field = Foo.class.getDeclaredField("value");
field.setAccessible(true);
Object value = field.get(bar);
That will get the value stored in a private variable in the class.
This is pretty ugly and you probably shouldn't do it but if you really need to avoid altering the class you're testing with then it should do the trick.
Related
I have defined a class which acts like a model/pojo. The class has many keys/variable. I have implemented custom solution for storing the POJO on disk for future uses. Now what I want to do is that whenever any value in the class/POJO is changed, I should call a method which sync the fresh changes with file on disk.
I know I can define setter for each variable. But it's quite tedious to do for 100s of direct and sub fields, and even if I define setter for each field, I have to call sync function from all the setters.
What I need is single proxy setter or interceptor for all change pushes to variables in class.
I am using this in an android application, so whenever the user enters new details in his/her account I have to store those details at that specific instance of time for preventing the data loss. I am using GSON for serialising and de-serialising.
Sorry for using vague terminologies, never been to college :|.
The easiest solution is indeed to use a setter. You only have to create one for each field you want to monitor, and most IDEs generate them for you or you can use something like Koloboke, so it being tedious isn't really an argument.
A proxy class or reflection would also be possible, but that is pretty hacky. Another way would be an asynchronous watcher/worker that checks for changes in you POJO instances, but even that seems unnecessarily complicated.
Apart from that you might need to rethink your POJOs structure if it has that many fields.
The problem with persisting(in your case writting to a disk) entity on each property update is that most of the updates are modifying more then one property. So in case you have a code like this:
entity.setA(avalue);
entity.setb(bvalue);
entity.setc(cvalue);
You would write it to the disk 3 times, which is probably not a best way, as it takes more resources, and 2 out of 3 writes are unnecessary.
There are several ways to deal with it. Imagine you have some service for saving this data to a disk, lets name it entityRepository. So one option is manually call this entityRepository each time you want to save/update your entity. It seems to be very uncomfortable, comparing to calling this automatically on setter call, however, this approach clearly shows you when and why your entity is persisted/updated, in your approach it's unclear, and can lead to some problems future problems and mistakes, for example, in future you will decide that you now need to update one of the properties without immideately persisting, then it appears that you will need 2 setter, one with update, and one without...
Another way is to add version property, and when its setter is called inside this setter call entityRepository.save(this).
The other way is to look at AOP, however anyway I don't recommend persist entity on any change, without having control over it.
You are talking about data binding. There is no built-in way for that so you have indeed to sync it yourself. Look into How to Write a Property Change Listener. There are also lots of other approaches to this, but as said no built-in way.
how
lets say i have this class
#ImmutableWannabe
public class ConfigurationHolder {
#ImmutableButHowToMakeSureNoTwoThreadsOverrideOneEachOtherWhenReplacingReference
private Map<System, Configuration> mySysConfig = ImmutableMap.builder<>getSomeConfigurations....build();
ConfigurationHolder(copy constructor) {
mySysConfig = ImmutableMap.builder().of(inputSysConfig);
}
}
Now lets say one of the systems configuration has updated and i need to update this map of however I need to do it in a thread safe way. which means if two threads try to update the same configuration of same system data should be consistent and they should not override one each other.
How did immutability help me here? As far as i can see i still need to do locking if yes how to do it properly?
so my general question is: isn't it the case that any immutableObject which can change over system time will cause us to need to lock the code that will need to change its ImmutableObjectHolder? I don't get it...
can someone please give a proper example of an ImmutableMap + Holder for that Map + proper "client" code that knows to update this ImmutableMapHolder with updates to the internal Map?
thanks
Assuming your map is some instance variable, the simplest way it to make it volatile. Alternatively, make a getter and setter for it and make them synchronized. i.e., use standard techniques. And note that this won't help if the client tries to be clever and cache the value in a local variable. (I've bitten myself with this bug a couple of times.)
I guess as an alternative you could setup some MyImmutableChanged event/listener.
And, you are correct, immutability doesn't solve every threading problem.
My Eclipse does a number of code-cleaning actions automatically when I save a Java file, among them adding final to private fields where possible.
Will this conflict with Hibernate's ability to inject entity properties into private fields?
#Id
private final Long id = null; // Eclipse made this "final"
// but Hibernate needs to set the id
Should I turn this save action off?
Update: I have tested the application and also looked at it with a debugger, and Hibernate does indeed reset the "final" field, so things continue to work okay. But is this guaranteed to work? For example, are there no VM or compiler optimizations that rely on a field really being final. Those would probably break. On the other hand, being able to set private fields via reflection seems to be a supported scenario, so the same thinking probably applies to final as well?
Even if it work, don't do it.
A final field can be written exactly once, and parts of the java memory model based on this fact.
I found this blog http://www.polygenelubricants.com/2010/03/modifying-static-final-fields-through.html which showed that it is possible to set an final via reflection with an real Hack. (But please don't do this in any real application.)
And this answer to an related question: Is there any way to declare final fields for Hibernate-managed objects?
In your case the simplest soultion would be: make the field mutable, and provied only a getter but not a setter.
hmm interesting question. I think on persisted objects you probably don't want to autoset final, for exactly the reason you mention.
It will definitely be a problem if your class has some sort of functionality where you do something like
setProperty(int prop) {
this.prop = prop;
fireChanged(); // updates other fields that depend on this one
}
which I have seen in a professional context. Although maybe here the plugin is smart enough to not make it final.
If you want to make your objects immutable, you could have your persistent class return an immutable subclass of itself, where the fields are private....
So there are advantages and disadvantages to that plugin. I guess you can do it either way, as long as you have tests to verify the auto-generated finals don't get in the way. Personally I would not use that plugin though -- I would look at the IDE warning and pick and choose my finals...
I have an odd situation where i want to be able to be able to persist a variable in memory.. like a global variable I can pin in the JVM.
Is this possible? I remember doing something similar in college, but can't find it by googling. I have a logic problem that has some artificial constraints that make this the best possible solution.
EDIT 1:
I will need to update the value of the variable.
EDIT 2 :
I appreciate the responses guys. I'm a .net programmer and hadn't used java since college. Thanks again.
Yes, using a static field:
public class GlobalVariableHolder {
public static int globalVariable;
}
Note, however, that this is considered a bad practice and can lead to unexpected results that are hard to debug. The way to not use a global variable is to pass it around as an argument or methods where you need it.
If you are still sure you need this, in order to guard yourself as much as possible, use synchronization. Even better, if the variable is going to be primitive (int, long, etc), you can use AtomicInteger's getAndAdd() or addAndGet() method.
Usually you will end up storing these things in some kind of a global class--a class that is accessible from anywhere and has a controlled number of instances.
Singletons are commonly used for this. If you look up the pattern for a singleton and store your variable in that singleton (add a setter and a getter) you are on your way.
Doing this (as opposed to a public static variable) will give you some level of access control and traceability--for instance you can put debug statements in the getter if you find you are getting unpredictable results.
In the long run setters and getters and singletons are all bad code smells but no where near as bad as a settable public variable.
Later you may want to move the code that manipulates that variable into the singleton object and possibly convert the singleton to something you can fetch via IOC, but having a singleton is a much better place to start than with a public static.
Do you mean something that will exist across multiple invocations of java.exe, or do you mean a single variable that will be the same location in memory regardless of which thread within java.exe access it? Or do you mean a variable that can only be accessed if you're using JRockit? Or maybe just the JVM on your dev machine, but not on another system?
In the first case, you'd need another way to store it, like a config file.
In the second case, like Bozho says, use the static keyword.
In the third case, you'd probably need to use the System class and determine the JVM manufacturer (Assuming that's available from System - I'm not sure off the top of my head, and you'll learn more by looking up the API yourself).
In the fourth case, you're pretty much back to a config file.
Its not going to win any awards but this should work:
package mypackage;
public class MyGlobal {
public static String MY_GLOBAL_VAR = "my variable";
}
Any class within that JVM instance would be able to access MyGlobal.MY_GLOBAL_VAR.
Updated to allow update.
I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html