I make singleton class and use this class object in different class this code work fine in eclipse
but when i make runnable jar than it take empty hashmap list i don't know why my code...
My singleton class
public class PointCalculate {
public HashMap<String, Float> calPoint;
private static PointCalculate instance;
private PointCalculate(){
calPoint = new HashMap<String, Float>();
}
public static PointCalculate getInstance(){
if(instance==null){
instance = new PointCalculate();
}
return instance;
}
public void calculatePoint(String uid ,float point){
Float ps = instance.calPoint.get(uid);
if(ps==null) {
ps = point;
instance.calPoint.put(uid, ps);
}
else {
ps = point+ps.floatValue();
instance.calPoint.put(uid, ps);
}
}
}
and i am passing value from this class below....
public class Exp {
public void setpoint(){
PointCalculate obj = PointCalculate.getInstance();
obj.calculatePoint(rowkey, point);//rowkey and point come from file.....
}
}
now i am passing hashmap....
public static void main(String args[]) throws Exception {
PointCalculate obj = PointCalculate.getInstance();
SqlInsertPoint.givePoint(obj.calPoint);
}
but in SqlInsertPoint.givePoint() hashmap list will be empty i don't know why if any body know than help me
Thanks in advance
What is wrong with this code? In main you obtain an instance of PointCalculate, do not put any points into it, and pass it over to givePoint method. Since you didn't populate the HashMap, it should be empty.
On a separate note, static Singletons are difficult to get right, and in general should be avoided (couple good reasons). In your concrete case not only PointCalculate class is not thread-safe, but it also exposes calPoint to the whole world. So, anybody can run the following code and essentially override your instance.
PointCalculate.getInstance().calPoint = new HashMap();
Related
I'm learning to code java and I encountered some problems in which I could use help understanding how things work.
I've made a list containing "Images", on my Main class, called "myList".
public class Main{
public static void main(String[] args) {
List<Images> myList = new ArrayList<Images>();
...
And I want to access it on this "System" class. But it doesn't seem to let me.
The plan is to access a position (the 3rd, in this example) on the given list (list.get(2)).
So I created the method "work".
//Example
public class System{
public static boolean work(List<Images> list){
if( list.get(2).equals(Something) )
return false;
else ... return true;
}
On this same System class I'm trying to use the method "work", giving it the List that I created on my Main class (myList).
public class System{
...
if( work(myList) ) //Don't know how to reffer to myList
return something;
Gives me the error "myList cannot be resolved to a variable".
So the problem is how to reffer to the list I made on my Main, named "myList".
Not sure if I explained that too well but any suggestions?
Make a List a property of System class, then pass it in the constructor
public class System {
private List<Images> images;
public System(List<Images> images) {
this.images = images;
}
//your other methods
}
Ah, in your main you should also pass the list:
System system = new System(myList);
Another option its to make myList public static and access it like this:
Main.myList
Declare one helper class and declare your list with setter and getters. Mainatin a singleton object of this class and use that list then in different other classes.
you need to make sure its accessible.
Right now your list is scoped the main() function. which is static to boot.
You need to make it accessible. You can do this by storing it in a static variable and having a static function return it.
Or you pass the main object along to other object, so they can access it.
public class Main {
private List<Images> myList = new ArrayList<Images>();
public static void main(String[] args) {
new Main(args);
}
public Main(String[] args) {
myList.add('foo.png');
myList.add('bar.png');
System mySystem = new System(this);
}
public List<Images> getImages() {
return myList();
}
}
public class System{
Main global;
public System(Main main) {
global = main;
}
public void doSomething() {
Iterator<Images> it = global.getImages().iterator();
while(it.hasNext()) {
Images images = it.next();
}
}
}
I am working on a project in java and am quite new to the language and OOP. My dilema is that I want to carry out a task/function from a specific class based on the value of a variable.
This is kind of what I am trying to achieve.
class mainClass{
String option;
public static void main(String[] args) {
mainClass main = new mainClass();
}
mainClass(){
secondClass sC = new secondClass();
thirdClass tC = new thirdClass();
switch (option){
case "1" :
sC.doSomething();
case "2" :
tC.doSomething();
}
}
}
class secondClass{
void doSomething(){
System.out.println("1");
}
}
class thirdClass{
void doSomething(){
System.out.println("2");
}
}
The reason I don't want to do this, is because if I want to add a fourth, fifth, sixth class etc... I would have to update the switch.
I tried using a hashmap. Where I assigned secondClass the key of "1". But then I would have to cast the object, but this brings me back to the original headache of not knowing what class would need to be called in advance.
So then I tried using a hashmap like this,
HashMap<String, Object> map = new HashMap<String, Object>();
Which I could then do map.get("1") but then now I can't call any of the methods for the class in question.
If I need to use a large switch statement I will, but I am actively seeking a more efficient alternative.
You were right to use a Map but you were also right to balk at casting. However, nowadays with generics you can get around all that:
interface DoesSomething {
// An object implementing this interface does something.
public void doSomething();
}
// Class that does something.
class FirstClass implements DoesSomething {
#Override
public void doSomething() {
// What FirstClass does.
}
}
// Another class that does something.
class SecondClass implements DoesSomething {
#Override
public void doSomething() {
// What SecondClass does.
}
}
// How I know what to do. Map the string to a DoesSomethng.
Map<String, DoesSomething> whatToDo = new HashMap<>();
{
// Populate my map.
whatToDo.put("1", new FirstClass());
whatToDo.put("2", new SecondClass());
}
public void doSomethingDependingOnSomething(String something) {
// Look up the string in the map.
DoesSomething toDo = whatToDo.get(something);
// Was it in there?
if (toDo != null) {
// Yes! Make it do it's thing.
toDo.doSomething();
}
}
If you want to avoid using Reflection (wich is discouraged here), you should consider a simple SAM-Interface:
public interface Doable { public void doSomething(); }
and have all classes implement the interface (no other changes required in these classes) and having a Map<String, Doable> and calling
if (map.containsKey(option)) map.get(option).doSomething();
// Or (may be a little faster)
Doable opt = map.get(option);
if (opt != null) opt.doSomething();
If your implementations have different methods, you'll most likely be bound to use Reflection to get the declared methods and compare by String.
I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.
I am trying to write a unit test for a legacy code. The class which I'm testing has several static variables. My test case class has a few #Test methods. Hence all of them share the same state.
Is there way to reset all static variables between tests?
One solution I came up is to explicitly reset each field, e.g.:
field(MyUnit.class, "staticString").set(null, null);
((Map) field(MyUnit.class, "staticFinalHashMap").get(null)).clear();
As you see, each variable needs custom re-initialization. The approach is not easy to scale, there are a lot such classes in the legacy code base. Is there any way to reset everything at once? Maybe by reloading the class each time?
As a possible good solution I think is to use something like powermock and create a separate classloader for each test. But I don't see easy way to do it.
Ok, I think I figured it out. It is very simple.
It is possible to move #PrepareForTest powermock's annotation to the method level. In this case powermock creates classloader per method. So it does that I need.
Let's say I'm testing some code involving this class:
import java.math.BigInteger;
import java.util.HashSet;
public class MyClass {
static int someStaticField = 5;
static BigInteger anotherStaticField = BigInteger.ONE;
static HashSet<Integer> mutableStaticField = new HashSet<Integer>();
}
You can reset all of the static fields programmatically using Java's reflection capabilities. You will need to store all of the initial values before you begin the test, and then you'll need to reset those values before each test is run. JUnit has #BeforeClass and #Before annotations that work nicely for this. Here's a simple example:
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.Map;
import java.util.HashMap;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class MyTest extends Object {
static Class<?> staticClass = MyClass.class;
static Map<Field,Object> defaultFieldVals = new HashMap<Field,Object>();
static Object tryClone(Object v) throws Exception {
if (v instanceof Cloneable) {
return v.getClass().getMethod("clone").invoke(v);
}
return v;
}
#BeforeClass
public static void setUpBeforeClass() throws Exception {
Field[] allFields = staticClass.getDeclaredFields();
try {
for (Field field : allFields) {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
Object value = tryClone(field.get(null));
defaultFieldVals.put(field, value);
}
}
}
catch (IllegalAccessException e) {
System.err.println(e);
System.exit(1);
}
}
#AfterClass
public static void tearDownAfterClass() {
defaultFieldVals = null;
}
#Before
public void setUp() throws Exception {
// Reset all static fields
for (Map.Entry<Field, Object> entry : defaultFieldVals.entrySet()) {
Field field = entry.getKey();
Object value = entry.getValue();
Class<?> type = field.getType();
// Primitive types
if (type == Integer.TYPE) {
field.setInt(null, (Integer) value);
}
// ... all other primitive types need to be handled similarly
// All object types
else {
field.set(null, tryClone(value));
}
}
}
private void testBody() {
assertTrue(MyClass.someStaticField == 5);
assertTrue(MyClass.anotherStaticField == BigInteger.ONE);
assertTrue(MyClass.mutableStaticField.isEmpty());
MyClass.someStaticField++;
MyClass.anotherStaticField = BigInteger.TEN;
MyClass.mutableStaticField.add(1);
assertTrue(MyClass.someStaticField == 6);
assertTrue(MyClass.anotherStaticField.equals(BigInteger.TEN));
assertTrue(MyClass.mutableStaticField.contains(1));
}
#Test
public void test1() {
testBody();
}
#Test
public void test2() {
testBody();
}
}
As I noted in the comments in setUp(), you'll need to handle the rest of the primitive types with similar code for that to handle ints. All of the wrapper classes have a TYPE field (e.g. Double.TYPE and Character.TYPE) which you can check just like Integer.TYPE. If the field's type isn't one of the primitive types (including primitive arrays) then it's an Object and can be handled as a generic Object.
The code might need to be tweaked to handle final, private, and protected fields, but you should be able to figure how to do that from the documentation.
Good luck with your legacy code!
Edit:
I forgot to mention, if the initial value stored in one of the static fields is mutated then simply caching it and restoring it won't do the trick since it will just re-assign the mutated object. I'm also assuming that you'll be able to expand on this code to work with an array of static classes rather than a single class.
Edit:
I've added a check for Cloneable objects to handle cases like the HashMap in your example. Obviously it's not perfect, but hopefully this will cover most of the cases you'll run in to. Hopefully there are few enough edge cases that it won't be too big of a pain to reset them by hand (i.e. add the reset code to the setUp() method).
Here's my two cents
1. Extract static reference into getters / setters
This works when you are able to create a subclass of it.
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public void doSomethingWithMap() {
Object a = something.get("Object")
...
// do something with a
...
something.put("Object", a);
}
}
change into
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public void doSomethingWithMap() {
Object a = getFromMap("Object");
...
// do something with a
...
setMap("Object", a);
}
protected Object getFromMap(String key) {
return something.get(key);
}
protected void setMap(String key, Object value) {
seomthing.put(key, value);
}
}
then you can get rid of dependency by subclass it.
public class TestableLegacyCode extends LegacyCode {
private Map<String, Object> map = new HashMap<String, Object>();
protected Object getFromMap(String key) {
return map.get(key);
}
protected void setMap(String key, Object value) {
map.put(key, value);
}
}
2. Introduce static setter
This one should be pretty obvious.
public class LegacyCode {
private static Map<String, Object> something = new HashMap<String, Object>();
public static setSomethingForTesting(Map<String, Object> somethingForTest) {
something = somethingForTest;
}
....
}
Both ways are not pretty, but we can always come back later once we have tests.
I want a hard reference class in my Java code, but, of course, there isn't one. Is there some other way to do what I want, or should I make my own class?
This comes up with anonymous classes in methods where I want the anonymous class to set the return value for the method.
For example, given
interface Greeting {
void greet();
}
I want code like the following:
// Does not compile
static void hello(final String who) {
String returnValue;
Greeting hello = new Greeting() {
public void greet() {
returnValue = "hello" + who;
}
};
hello.greet();
System.out.println(returnValue);
}
I can fake it using a list:
static void hello(final String who) {
final List<String> returnValue = new ArrayList<String>();
Greeting hello = new Greeting() {
public void greet() {
returnValue.add("hello" + who);
}
};
hello.greet();
System.out.println(returnValue.iterator().next());
}
But I want to not use a list. I can write a StrongReference class that solves this:
static class StrongReference<T> {
private T referent;
public void set(T referent) {
this.referent = referent;
}
public T get() {
return referent;
}
}
which makes my method clearer:
static void hello(final String who) {
final StrongReference<String> returnValue = new StrongReference<String>();
Greeting hello = new Greeting() {
public void greet() {
returnValue.set("hello" + who);
}
};
hello.greet();
System.out.println(returnValue.get());
}
For my contrived example, I could have greet() return a String, but I'm working with much more complex classes, where the setting is deep within a database call that the base class manages. The instances have many different types they want to return, so I've just been using the List trick.
My questions are: Is there a better way to do this? What's wrong with my StrongReference class? Has anyone written a StrongReference in a library somewhere?
If you want something from the standard API, perhaps an AtomicReference would do?
It has void set(V value) and a V get() methods. Unless you have multiple threads involved, just see the synchronization mechanism as a bonus ;-)
A common idiom
final String[] result = { null };
result[0] = ...;
Looks good but I think you should make some kind of synchronization since another thread might set the value.