-1

I have a class in android (java) I forced to create that class every second (new className() ) because variable is final . this use a lot of memory . I can not change the class because it is implemented in a library

I want : when at first create className and OS allocates a memory place, when I create my class again , it replace to that place which allocated at the first time. Or How I can change final variable?

3 Answers3

1

Singleton Class example :

public class SomeClass {
  private static LibraryClass libraryClass;
  public static LibraryClass getInstance() {
    if(libraryClass == null) {
      libraryClass = new LibraryClass();
    }
    return libraryClass;
  }
}

Then you can call it : LibraryClass libraryClass = SomeClass.getInstance();

Randyka Yudhistira
  • 3,612
  • 1
  • 26
  • 41
  • I want to set a value to final variable in libraryclass and I set value only in constructor, in your example I can not set value to variable – Telegram Instagram May 24 '17 at 06:39
  • @TelegramInstagram if that value fixed at the beginning it's trivial to adapt constructor invocation in snippet above. If that value changes, since it's `final`, you cannot reuse the instance. – Hugues M. May 24 '17 at 07:06
0

You can write a reset() method on your class, which resets all fields of the object to the initial state.

When you want to create a new object, without creating a new object, call reset() on old object and re-use it.

Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
  • I can not change the class because it is implemented in a library – Telegram Instagram May 24 '17 at 05:55
  • @TelegramInstagram, if the class has setters for all fields, you can write a utility method `resetObject(LibObject object)` in your code which calls setters of all fields of the object to reset them to initial value. Then, you can call this method when you want to re-use the object. – Lahiru Chandima May 24 '17 at 05:57
  • it is my problem taht I can not write(set) method in that class, and variables is final , I can not change class at all . – Telegram Instagram May 24 '17 at 06:01
  • @TelegramInstagram, you may be able to set values of private final fields of this object with the method described in following answer. https://stackoverflow.com/a/3301720/1015678 – Lahiru Chandima May 24 '17 at 06:16
  • @LahiruChandima Good point. Does that work on Android too? (I mean the technique to bypass `final` linked in previous comment, not your answer ☺) – Hugues M. May 24 '17 at 07:09
0

I solved my problem:

By this code:

Field modifierslatitude = className.class.getDeclaredField("latitude");
modifierslatitude.setAccessible(true);
modifierslatitude.set(classNameObjectThatFirstCreate, location.getLatitude() + MainActivity.y * 0.0002);

in fact I changed final variable without create new class again and again