This question already has answers here:
Java Reflection: How to get the name of a variable?
(8 answers)
Closed 7 years ago.
I'm facing following problem: I have to give names to many thousands of GUI-Elements. Would be nice if it could work a script like:
JMenuItem myMenuItem = new JMenuItem();
myMenuItem .setName(this.getClass().getSimplename() + "." + myMenuItem .get??)
Would be nice if I could set the name of the element to "Classname.myMenuItem".
Is there any way to get the name (variable name ofc, not JMenuItem.getName()) of the variable?
You can do this for field via reflection: see Field.getName().
You cannot do it for local variable, they basically don't have any name after the code is compiled (well, in debug info they have but it's not easily accessible and understandable unless you implement debugger :-) ).
What you want is not possible. Even if some information about variable names is present in the class file, you still have to remember that there is a difference between the variable and the object it refers to. There can be any number of variables (local variables, member variables, parameters, etc) that refer to the same object. Keeping track of the names of all of those variables would impose too much of a run-time overhead.
Related
This question already has answers here:
Get variable by name from a String
(6 answers)
Accessing the value of a variable by its name as string in Java
(2 answers)
Closed 5 years ago.
How can I access the variable value by providing the String that contains name of that variable?
Like this:
int var1 = 123;
getVariableByName("var1");
It should return 123
I know that I can create a HashMap or something...
But can I do this shortly, without a couple of code?
I need to create some objects with similar data, so I did this:
(I'm working with android)
String string2="bla";
String string2="bla-bla";
String string3="bla-bla-bla"
for(int i=1; i<=2; i++){
TextView tv = new TextView;
TextView.setText(getValueOf("string"+i));
}
Just it isn't smart to make a huge HashMap if you need to create a lot of objects. There should be a way to do it optimised...
You can't do that with local variables in Java. Local variables are variables you define inside a method. The names do not survive compilation step and are not available at runtime.
You can lookup fields via reflection via Foo.class.getField or obj.getClass().getField
This question already has answers here:
Why are local variables not initialized in Java?
(16 answers)
Closed 6 years ago.
instance and static variables will be initialized with a default values if we don't initialize with our own values but it doesn't happen with local variables.
Why they designed like so ?
The reason we have default values at all is that it's was decided it was too complicated to determine if a variable is initialised before it is used (unless it's final) This is because you could call methods in any order.
For local variable it can determine whether you have used a variable before you gave it a value, so this check prevents you using uninitialised values to avoid errors in your code.
This question already has answers here:
Why does BufferedInputStream copy a field to a local variable rather than use the field directly
(3 answers)
Closed 6 years ago.
In Netty I have seen object member variables assigned locally in class methods quite frequently. Is this a matter of style or is there a programmatic benefit?
I have included a code snippet below:
public ChannelFuture bind() {
validate();
SocketAddress localAddress = this.localAddress;
if (localAddress == null) {
throw new IllegalStateException("localAddress not set");
}
return doBind(localAddress);
}
I usually see that pattern when multi-threading is a concern. For example, if another thread may alter the member value or null it after the null check, yet it is still a valid use case for member access to occur at that point. Or the code is trying to avoid locks/synchronization. So instead the member is copied to a local and all further operations are done using the local copy to prevent a null access.
This question already has answers here:
Difference between local variable initialize null and not initialize?
(6 answers)
Closed 7 years ago.
My code below is compile error.
The local available may not has been initialized
String str;
my_obj.setValue(str);
and fixed by this
String str = null;
my_obj.setValue(str);
So is null instance of anything? What is the difference between null and not initialized.
Why does it work for this way?
My Class
class MyClass {
String str;
}
I have initialized obj not obj.str. but no such a compile error that ways...
MyClass obj = new MyClass();
my_obj.setValue(str);
I already read what all of you recommend before I post this questions. Maybe it duplicated, but I didn't get any idea form those.
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
Local variables must be initialized before they are accessed.
not initialized means, that you have not created object for that instance. Assigning a value will create a object to use it.
String str ;
Above code represents, that you have just declared it. But, can't use it until, it is assigned with some real value or null.
Reference to the question could be verified on this link
This question already has answers here:
Best practice for global constants involving magic numbers
(5 answers)
Closed 9 years ago.
Is it more practical to create a class named say, "Constants.java", and declare all the magic constants being use by the whole program, or put everything in properties file named ScreenMessage.properties? Values returned by Constants.java and in Properties file will be use to find a specific message from the database.
Example:
In Constants.java:
public static final String UNSUCCESSFUL_LOGIN = "MSGID001";
In ScreenMessage.properties:
UNSUCCESSFUL_LOGIN=MSGID001
[Added: 2013-May-18]:
Actually, the nature of this question is: if I put the Magic Constants in Constants.java, I can retrieve the constant's value by simply "Constants.UNSUCCESSFUL_LOGIN", but if I use properties file, I am embedding again another constant in the program because of the file name of the properties file, and it is more harder if the properties file is not in the same package than that of the class that will load the values of the properties file.
It depends of your need.
Pros and cons :
If you have some a Constants.java, you have access to the type of your constants, which is not the case with a properties file.
On the other side, a properties file can be changed without recompiling...
Here, you seem to need some IDs to retrieve some messages from the database. Those messages are strongly linked to the use cases of your application (specific code around each of your messages). Hence I think you should just use some enums as suggested by Juned Ahsan. They will be easier to refer in your code and you will avoid typos.
Best practice is not to have a Constants.java.
Put the constants near where they have relevance, like the way MAX_VALUE constant is define in the Integer and Long classes.
If you have a few constants of the same "type", like your message example, create an enum for them.
I believe enums are a good and acceptable choice these days to define constants
http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html