Reputation: 125
How to compare name of an object to a string in Java?
For example:
class_name obj = new class_name();
and I want to compare object name obj
with a string. What is the correct way to do that?
Upvotes: 3
Views: 3017
Reputation: 11087
If you want to access Local variables and if Source code is compiled with javac -g
option to retain debug info, Bytecode Library like ASM can be used to retrieve this details. See 4.3. Debug
Classes compiled with javac -g contain the name of their source file, a map- ping between source line numbers and bytecode instructions, and a mapping betwen local variable names in source code and local variable slots in bytecode. This optional information is used in debuggers and in exception stack traces when it is available
If you want to retrieve name of class level /Field variables you could use java reflection API.
Upvotes: 0
Reputation: 5440
You can check the Type of the Object Using instanceof
keyword
Look this examples for more details
public void checkType(Object param) {
if( param instanceof String) {
System.out.println("param is a String");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
}
I believe this is the right way to do it..!!
You can look here for more details
Upvotes: 0
Reputation: 129537
That can't be done directly in Java. Variable names are merely a convenience for the programmer and are not even kept track of after your code is compiled. You can instead use a Map
that maps string identifiers to their corresponding objects. Or you can add a name
field to your class which holds a string ("obj"
in your example):
ClassName obj = new ClassName("obj");
if (obj.getName().equals(...))
...
(Note that I've assumed a more standard naming convention.)
Upvotes: 8
Reputation: 1349
You can get the class' class name by invoking obj.getClass()
. You can't get the variable name of an object through normal means.
Upvotes: 0
Reputation: 3196
==
compares object references. It finds out if the two operands point to the same object.
If you want to check if two strings contain same characters, you need to compare the strings using equals
.
As to your concrete problem, it can't be done.
Upvotes: 0