Hi I've got a very simple class defined like this
public class Pokus {
public static String loginToken;
public String neco = "neco";
public Pokus() {
}
public static String getLoginToken() {
return loginToken;
}
public static void setLoginToken(String loginToken) {
Pokus.loginToken = loginToken;
}
}
When I create an instance of this class
Pokus pokus = new Pokus();
pokus.setLoginToken("bla1212");
In a debugger I can see that object pokus has a field/variable called "neco" but not that static variable "loginToken".
debbuger in Android Studio
Is there any way to see static variables as well as the non-static ones?
Thanks guys I knew all of this but didn't know that debugger is taking this into consideration. There is an option to show static field Settings > Build,Execution, Deployement > Debugger > Data Views > Java
Debugger shows it properly, pokus is instance of class Pokus so it have standard method and properties from class Pokus, static methods and properties are in Class not in instance of Class. Static properties are shared for every object created from class Pokus ( or for every component in program if their are public ) so debugger properly not shows them as properties of single instance.
To show static variable examine class not instance. When debugger stops on breakpoint You can use console and write Pokus.someStaticVar and You will see current value. Console is available in debugger - http://imgur.com/a/nHfEo.
You can right-click in the debugger's Variables area and select Customize Data Views...
In there, you can choose to add static and final static fields.
Static variables have the same values for all the instance of the class.Moreover they should be accessed using class and not an instance of the class. In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
That is the reason i think debugger does not show and it is correct behaviour
Related
I want to create an abstract class with a main method, to prevent developers who extend it from having to implement the main method. I also want to control what happens in the main method.
The abstract base class that I'm writing extends NanoHTTPD, and you start the server by calling ServerRunner.run() with the parameter being a class object of the type of the class that you want to run.
Here is what I have so far:
public abstract class FlexibleServer extends NanoHTTPD
{
public DeadSimpleMicroserver(int port)
{
super(port);
}
public static void main(String[] args)
{
ServerRunner.run(FlexibleServer.class);
}
}
The problem is that since this class is abstract, future developers will be extending the class, so I need the parameter to ServerRunner.run() to be the ACTUAL type of the subclass, so I can't use FlexibleServer.class.
I tried changing the parameter to this.class, but then I get the compile error that "this" cannot be referenced from a static context (because main() is static).
How can get a class object of the actual subclass from main()?
If the class that you're going to pass at runtime is dynamic, then you cannot call it with a hard-coded class name. You will have to change your call to run so that you pass it either an instance of the actual class, or you would have to dynamically load the class given, for example, main method arguments.
With the above change, your problem gets resolved.
For example, if you're loading the class dynamically:
ServerRunner.run(Class.forName(args[0]));
Assuming the app will be called with the actual class name.
Alternatives include redesigning your code such that either a class name, an instance, or class object is passed in by the caller
A framework I once worked on had a base class like this, and we added a method like this:
public abstract class FrameworkServer {
// framework stuff
protected static void main(String[] args, FrameworkServer instance) {
// parse args
// actually start the instance running
}
}
And a specific server instance would need to add its own main method like so:
final class MyServer extends FrameworkServer {
public static void main(String[] args) {
main(args, new MyServer());
}
}
There is a small bit of boilerplate here for each server, but that allows you do avoid reflection and to make the code much clearer. As a bonus, the concrete subclasses can now add their own arguments to their server's constructor, which is often very useful for unit-testing.
I am making a project in Android using Eclipse. In my app, I want to call a Java class for the second time.
Is there any way to keep a count of my Java class calls so as to do something on its second call?
Another possible solution might be having a Global class holding public properties.
public static class GlobalProperties
{
public Integer callNumber;
public String lastPerson;
}
Or having them private with get/set methods.
If you want to keep track of all of the calls to all instances of your Class, then you'll need something like private static int numberOfCalls, and increment it in each of your public methods. Otherwise, if you want an object-based counter, you need simply private int numberOfCalls.
just do this :
class A {
private static int countOfClassA = 0 ;
countOfClassA ++;
if(countOfClassA == 2)
//do sth
}
Thank you all for your help.
I solved it following this stackoverflow link:
How can I call a different xml on the second call of my onResume in Android Eclipse project
I have to maintain a code to add more flexibility to a final static variable in a class.
The variable is no more a global constant and may be changed.
The problem is that the class is in a common library and used in different projects.
Do you have an approach or a design pattern better than copying and pasting the class code from the common library to my specific application and refactoring it?
Example:
Commons project
Class CommonClass {
public final static var globalSomething = somethingGlobal;
public static method(){ //CommonClass.globalSomething is used here}
}
In my App (and other apps that reference commons) we can use the static attribute and also call the method:
---> var b = CommonClass.somethingGlobal;
---> var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
Expectations:
Ability to change CommonClass.somethingGlobal in my app and take these changes in call CommonClass.method()
I can modify (add methods) in the common class but i have to keep the same initial behavior (not to break other project referencing common project)
If I got you right, you want to implement this as a parameter.
Looking at your example:
var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
there is already something wrong with it. You shouldn't have to know that you have to set CommonClass.somethingGlobal correctly before calling the method. This way the client has to know the implementation, violating the principle of information hiding. If the value is required, introduce it as parameter:
Class CommonClass {
public static void method(var globalSomething){}
}
An alternative would be making both your variable and your method non-static and use a constructor:
Class CommonClass {
public var globalSomething = somethingGlobal;
public CommonClass(var globalSomething) {
this.globalSomething = globalSomething;
}
public void method(){}
}
PS: Your example code is not java. I corrected it partially in my answer.
I am currently working on a project that needs to be refactored (it was not written by me and the original developer is not around). I see in that application that rather many classes have only private constructors and one or more static methods (getter/setter of the current class object). They also have non-static methods. I give you one example:
Class UndoManager that manages the actions taken on the application for performing undo/redo. It has only private constructors. When the application is loaded, UndoManager.setManager() is called. This method loads the undo history from a file or constructs a new one using a private constructor.
Later, every class can access this instance of UndoManager with syngronized static method .getManager().
In code:
public class UndoManager extends SimpleObservable<UndoManager> {
private static UndoManager instance;
private final Stack<Action> undoHistory;
private final Stack<Action> redoHistory;
public synchronized static void setManager(UndoManager undoManager) {
UndoManager instance = getManager();
instance.clear();
instance.undoHistory.addAll(undoManager.undoHistory);
instance.redoHistory.addAll(undoManager.redoHistory);
instance.notifyObservers(instance);
}
public synchronized static UndoManager getManager() {
if (instance == null)
instance = new UndoManager();
return instance;
}
private UndoManager() {
this.undoHistory = new Stack<Action>();
this.redoHistory = new Stack<Action>();
}
/.../
}
In this application multiple classes are used like this. They are not helper classes but classes that should have only one instance.
My question is:
is this kind of access good style? If not, how would you refactor the class and it's access?
I'm sorry if it is a duplicate, but I have searched in stackoverflow and google for a while but somehow I didn't find a satisfying answer. Thank you for any help.
This looks like a singleton pattern.
It is part of the great familly of designs patterns you might know them.
The point of this is to ensure that there is only one instance of this object used throughout your application. Indeed when you call getManager() it will return a new instance the first time and next times it will return the formerly created instance.
it's a design pattern that called Singleton. it's a lazy load and used for managers classes and service classes for example. they are for classes that you want an instance but only one instance of them.
there is usually a method to get the instance like your getManager method and a private constructor like you have
When is static variable loaded, runtime or compile time? Can someone please explain it.
I would really appreciate the help.
Thank you.
The compiler optimizes inlineable static final fields by embedding the value in the bytecode instead of computing the value at runtime.
When you fire up a JVM and load a class for the first time (this is done by the classloader when the class is first referenced in any way) any static blocks or fields are 'loaded' into the JVM and become accessible.
A demonstration:
public class StaticDemo {
// a static initialization block, executed once when the class is loaded
static {
System.out.println("Class StaticDemo loading...");
}
// a constant
static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
// a static field
static int instanceCounter;
// a second static initialization block
// static members are processed in the order they appear in the class
static {
// we can now acces the static fields initialized above
System.out.println("ONE_DAY_IN_MILLIS=" + ONE_DAY_IN_MILLIS
+ " instanceCounter=" + instanceCounter);
}
// an instance initialization block
// instance blocks are executed each time a class instance is created,
// after the parent constructor, but before any own constructors (as remarked by Ahmed Hegazy)
{
StaticDemo.instanceCounter++;
System.out.println("instanceCounter=" + instanceCounter);
}
public static void main(String[] args) {
System.out.println("Starting StaticDemo");
new StaticDemo();
new StaticDemo();
new StaticDemo();
}
static {
System.out.println("Class StaticDemo loaded");
}
}
Output:
Class StaticDemo loading...
ONE_DAY_IN_MILLIS=86400000 instanceCounter=0
Class StaticDemo loaded
Starting StaticDemo
instanceCounter=1
instanceCounter=2
instanceCounter=3
Notice how 'Starting StaticDemo' does not appear as the first line of output. This is because the class must be loaded before the main method can be executed, which means all static fields and blocks are processed in order.
They are loaded at runtime.
Static means: that the variable belong to the class, and not to instances of the class. So there is only one value of each static variable, and not n values if you have n instances of the class.
run time when class is loaded.
- Have a look at initialization
The static fields are loaded when the class is loaded. This usually happens which the file object of a class is created, but it can be earlier if the class is used another way.
The static initialiser is thread safe and you can access the class in multiple threads safely. This is useful as a way to create a thread safe singleton without having to use a lock.
Note: the class can be loaded (and its static intialisation block run) more than once if multiple class loaders are used. Generally, loading the same class in multiple class loaders can be confusing and is avoided, but it is supported and does work.
How would you load a variable at compile time? The variable is initialized when the corresponding class is loaded. See the JVMS.
Loading is a runtime operation. Everything is loaded at runtime.
When you type java ClassName then class loads into JVM with static variables, so you don't need an object for it.
Where as instance variable loaded by JVM when the object is created.
Static fields gets loaded at the time of class loading in JVM.