This question already has answers here:
Getting enum associated with int value
(8 answers)
Closed 7 years ago.
i have a enum
public enum Category {
NonResidential("Non-Residential"), Residential("Residential");
private String category;
BuildingAssetCategory(String s) {
category = s;
}
public String getType() {
return category;
}
public void setType(String type) {
this.category = type;
}
}
I want to get the enum on the basis of value its having.
i have String of value Non-Residential, then how can i get the enum returning `NonResidential.
P.S i to want to create own magic rather then something java supports.
i have read out many question like this but i want different ans.
There is no magic here, since it's your own define field ('category') you should write your own static method to search by it. For example:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
btw ValueOf will work if you provide the enum name (e.g. "NonResidential") but it won't work for category name (e.g. "non-residential")
Use valueOf.
Category.valueOf("Non-Residential");
This will return you the enum.
Related
This question already has answers here:
Java: How to listen on methods invocation without registering each object explicitely?
(3 answers)
Listener on Method.invoke java
(1 answer)
Closed 3 years ago.
I have a class Person and I'd like to be aware of every call to getFirstName() method:
public class Person {
private String firstName;
private String lastName;
public Person() {...}
public String getFirstName() {
return this.firstName
}
//... Rest of getters and setters
}
So when somebody does this, I'd like to print out "Hello world" for example (actual use would be more complicated):
public class Main {
public static void main(String[] args) {
Person person = new Person("John", "Doe");
person.getFirstName();
}
However I want to do this without modifying Person class (at least NOT before compilation). I read sth about Observable pattern and Property Change Listeners, but they don't seem to be doing what I'd want. Is such thing even possible in java ?
I am using enum in java, Here is the enum
public enum AbuseSectionType{
MUSIC("Music"), DANCE("Dance"), SOLO("Solo"), ACT("Act")
private String displayString;
AbuseSectionType(String displayValue) {
this.displayString = displayValue;
}
#JsonValue
public String getDisplayString() {
return displayString;
}
public void setDisplayString(String displayString) {
this.displayString = displayString;
}
}
I am trying to get value AbuseSectionType.valueOf("Music"). I am getting no enum constant and found no error. I am supposed to have value MUSIC.
The name() of an enum is the name specified when declaring it, MUSIC in your case.
If we read the javadoc for valueOf():
Returns the enum constant of the specified enum type with the
specified name.
valueOf() is using the name() of the enum. But what you want to achieve is different, so you cannot use this method. What you can do instead is to make your own method that finds the value from your own field (displayString).
Here's an example:
public static AbuseSectionType fromDisplayString(String displayString)
{
for(AbuseSectionType type : AbuseSectionType.values())
if(type.getDisplayString().equals(displayString)
return type;
return null; //not found
}
The default valuOf() method will only retrieve the respective enmum if the exact spelling of the enum-definition is used. In your case you have defined the enum MUSIC so in order to get that one you have to do it like this: AbuseSectionType.valueOf("MUSIC");
In order to achieve what you seem to want you have to implement a method in the enum class by yourself. For your example you could do somthing like this:
public AbuseSectionType resolve(String name) {
for(AbuseSectionType current : AbuseSectionType.values()) {
if(current.displayString.equals(name)) {
return current;
}
}
return null;
}
use AbuseSectionType.valueOf("MUSIC") pass the name of enum. See java docs regarding use of valueOf
This question already has answers here:
What is Type<Type> called?
(3 answers)
Closed 7 years ago.
I am working on a Java application in which I found this class:
public class TipologiaGenerica<K> {
private K codice;
private String descrizione;
public TipologiaGenerica(K codice, String descrizione) {
this.codice = codice;
this.descrizione = descrizione;
}
public K getCodice() {
return codice;
}
public void setCodice(K codice) {
this.codice = codice;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
}
As you can see this class is declared as: TipologiaGenerica and K seems to be something like an object type that could be passed when a specific TipologiaGenerica object is created and that determinate the type of one of its inner field, this one:
private K codice;
Infact, somewhere else in the code, I find a TipologiaGenerica object creation:
TipologiaGenerica<String> dataPerLista = new TipologiaGenerica<String>(dataString, dataString);
What exatly mean? I think that doing in this way it is creating a specific TipologiaGenerica object having the inner codice field that is a String.
Is it my reasoning correct? What is the name of this specific use of Java? What are the most common purpose of this type of constructor?
It is called Generic Types. You can use them to generalize some classes / methods into typesafe code "templates".
Check the Oracle's tutorial regarding this topic
https://docs.oracle.com/javase/tutorial/java/generics/
Is it my reasoning correct?
yes.
What is the name of this specific use of Java?
Generics
What are the most common purpose of this type of constructor?
type safety
This is called generics in Java. The use of this type of programming is to ensure type safety and that you could reuse the same parent class by inserting various object types. for e.g. in your case, you have made
TipologiaGenerica<String>
Users can reuse the same class for other types, for e.g.
TipologiaGenerica<Integer>
This question already has answers here:
How can I get an Object's name in java?
(8 answers)
Closed 7 years ago.
when an object is created how can i get the name of that object ??
for example let's consider a class Book:
public class Book {
private String name;
private int pages;
public Book(String name, int pages) {
this.name = name;
this.pages = pages;
}
}
// now i create an object of this class
Book book = new Book("Java",100);
i want to get the name of the object created that is "book", is there any way to get it ?
i tried the toString(), function and it does not work it prints something like this: #3d4eac69
If you mean the name property, you can't with your code as written. You'd need to either make name public, or provide a public getter for it
If you mean the name of the class, it would be
book.getClass().getName()
If you mean the name of the variable you've assigned it to (book), you can't, that isn't information available at runtime (outside of a debug build and debugger introspection).
You have to create the getter method in Book class. Would be like:
public String getName() {
return this.name;
}
And then you would call:
book.getName();
Use:
book.getClass().getName();
Every object in Java has getClass() method:getClass() documentation
And every Class object has its name:
getName() documentation
I have an enum class, but I want to display string based on user system language. For example, If the system is English , it should display 1 , 2 ,3
. But if the System is Chinese, the display should totally be different like "一", “二”, “三”. (一 means 1 in Chinese, 二 means 2 in Chinese).
Here is my code
public enum OrderType {
ONE("1"), TWO("2"), THREE("3")
private String name;
private OrderType(String name) {
this.name = name;
}
public String toString() {
return name;
}
public static String getEnumByString(String code) {
for (OrderType e : OrderType.values()) {
if (code.equals(e.name)) {
return e.name();
}
}
return null;
}
}
The enum works fine in android, Can I define the String in the value folder,
Like values-iw, values-ru... And how can I use that?
UPDATE:
I also want to use constructor to initialize the enum string. Just like
private OrderType(String name) {
String temp = getResources().getString(R.string.name);
this.name = temp ;
}
But I do not know how to pass parameter of R.string.parameter..
Second, how Can I use getResources() function in enum class
Just provide the String resource ID as a parameter to your Enum:
public enum OrderType {
ONE(R.string.order_type_one),
TWO(R.string.order_type_two)
private final int mTextResourceId;
OrderType(int resourceId) {
mTextResourceId = resourceId;
}
public int getTextResourceId() {
return mTextResourceId;
}
}
Provide these strings in each desired resource folder, e.g.:
res/values/strings.xml
res/values-es/strings.xml
res/values-fr/string.xml
Then, when you want to consume this in a TextView somewhere:
myTextView.setText(myOrderType.getTextResourceId());
No Context passing required, and it is determined at runtime based on the current locale.
You must know that enums are initialized statically. Each of ONE, TWO, THREE is static.
In android to use resources, such as strings, you need a context.
Generally, you can not access Android context in static methods or initializes, therefore you can't use them with enums.
Even if you could use a hack to make android context statically available you would still have issues :
you'd need to ensure none of your OrderType enums accessed before Application#onCreate
strings in your enums won't reflect runtime language changes
Edit
I hope it is clear that you can not reliably initialize your enums with string resources.
You could, however, associate static id of a string (R.string.string_name) with your enum and obtain needed resource string later using a context, as proposed in kcoppock's answer.
You should keep the strings in your string xml resource. That way you can get it from there into your code. For example like this:
String one = getResources().getString(R.string.num_one);
Then you just put a strings.xml file with overloading values in the language folders you want (values-ru, values-sv etc.)
For tasks of that kind use localizations.
"google on i18n java"
and
"android app localization"
public enum OrderType {
One(mActivity.getString(R.string.One)), Two(mActivity.getString(R.string.Two));
private String name;
private OrderType(String name) {
this.name = name;
}
public String toString() {
return name;
}
public static String getEnumByString(String code) {
for (OrderType e : OrderType.values()) {
if (code.equals(e.name)) {
return e.name();
}
}
return null;
}
}
also Here is the link, which I think is best way solve the porblem. This developing for API level 11 currently, however this code should run on higher versions. After a quick review in API 16 I did not see an existing core Android solution to this problem, if you know of one please post below and share.