Java access enum field from outside - java

How I can access the Name field?
public class Animals {
public enum animal{
a1("CAT", 4),
a2("DOG", 4);
}
String Name;
int E;
public animal(String Name, int E){
this.Name = Name;
this.E = E;
}
}

This can be done, but you have a number of syntax errors. The key is to provide getter methods for the enum member variables.
public enum Animal {
a1("CAT", 4), a2("DOG", 4);
private String Name;
private int E;
private animal(String Name, int E)
{
this.Name = Name;
this.E = E;
}
public String getName() {
return Name;
}
public int getE() {
return E;
}
}
You could then access these values anywhere in the rest of your program.
Animal.a1.getName();

Assuming you have an inner enum like this:
public class Animals {
public enum Animal {
a1("CAT", 4), a2("DOG", 4);
final String Name;
final int E;
private Animal(String Name, int E) {
this.Name = Name;
this.E = E;
}
public String getName() {
return Name;
}
}
}
You can get the name using (field so no parenthesis)
Animals.Animal.a1.Name
but better to make all fields private and use the getter:
Animals.Animal.a1.getName()

If I understand correctly, I believe the OP is asking:
“Given a string, "a1", return an object of type Animal with the value Animal.a1”
… in which case, the method you're looking for would be Enum.valueOf(Class,String)
String enumName = "a1";
Animal a = Enum.valueOf (Animal.class (enumName));
if (null == a) {
// error handler …
} else {
// do something interesting with “a”
}

Related

How to do validation for set boolean and double

I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double? below is the code i wrote for string.
public class Person
{
private String name;
private String id;
private boolean isNew;
private double bonus
public Person()
{
this("Unknown","unknown",true,0.0);
}
public Person(String id,String name,boolean isNew,double bonus)
{
setId(id);
setName(name);
setIsNew(isNew);
setBonus(bonus);
}
public getId()
{
return id;
}
public getName()
{
return name;
}
public setId()
{
this.id = id;
}
public setName()
{
this.name = name;
}
public void display()
{
System.out.println("Id:" + id);
System.out.printoutln("Name:" + name);
}
// setter validation for string
public void setName(String name)
{
if(name == null)
{
throw new IllegalArgumentException("A valid name must be provided ");
}
name = name.trim();
if(name.length() ==0)
{
throw new IllegalArgumentException("Name must not be blank ");
}
this.name = name;
}
// setter validation for id
public void setId(String id)
{
if(id == null)
{
throw new IllegalArgumentException("A valid id must be provided ");
}
id = id.trim();
if(id.length() ==0)
{
throw new IllegalArgumentException("Id must not be blank ");
}
this.id = id;
}
}
I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double?
When you want return value you have to declare returned type for example "public String getId()" instead "public getId()".
Setter expects a parameter. Example: "public setId(String id)".
All args constructor should looks like:
public Person(String name, String id, boolean isNew, double bonus) {this.name = name; this.id = id;this.isNew = is;this.bonus = bonus; }
For boolean argument constructor expect value. If you want validate something you can change type to Boolean and handle NullPointerExeption.
Or create custom exception:
public class MyWrongBooleanException extends RuntimeException
{
public IncorrectFileExtensionException(String errorMessage, Throwable err)
{
super(errorMessage, err);
}
}

How to get enum by user defined name in java?

I am defined a enum in Java 8 like this:
public enum Cflb implements IBaseEnum {
没收违法所得("没收违法所得、没收非法财物", 2),
暂扣或者吊销许可证("暂扣或者吊销许可证、暂扣或者吊销执照", 4);
private String name;
private int value;
public void setName(String name) {
this.name = name;
}
public void setValue(int value) {
this.value = value;
}
Cflb(String name, int value) {
this.name = name;
this.value = value;
}
#Override
public String getName() {
return name;
}
#Override
public int getValue() {
return value;
}
}
How to get enumn by "暂扣或者吊销许可证、暂扣或者吊销执照"? attention:not get the enumn by value. The code maybe like this:
Cflb cflb = getEnumnByInternalName("暂扣或者吊销许可证、暂扣或者吊销执照");
Loop over the enum constants using values() and compare the name:
static Cflb getEnumnByInternalName(String iname) {
for(Cbfl c : values()){
if(c.name.equals(iname)){
return c;
}
}
return null; //or throw an Exception, whatever you need
}
Then you can use it like this:
Cflb cflb = Cflb.getEnumnByInternalName("暂扣或者吊销许可证、暂扣或者吊销执照");
And as #khelwood mention above: Remove the setters.

Print Different Object Data From ArrayList in Java

Is there some way to print different data from an ArrayList containing different objects?
For example, I created two basic classes:
import java.util.*;
class Furniture{
String name;
int weight;
Furniture(String name, int weight){
this.name = name;
this.weight = weight;
}
String getName(){
return name;
}
int getWeight(){
return weight;
}
}
}
class Resident{
String name;
Resident(String name){
this.name = name;
}
String getName(){
return name;
}
}
Then I stored them in an ArrayList<Object> and wanted to print the names, by using declared below printArrayList method:
public class Main{
public static <E> void printArrayList(ArrayList<E> arrayToPrint){
for(E element : arrayToPrint){
try{
System.out.println(element.getName());
}
catch(Exception e){
System.out.println("Exception e: " + e);
}
}
}
public static void main(String []args){
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
printArrayList(arrayList);
}
Now, I know that not all objects can have a variable name or declared get method, therefore I tried to exclude these cases by try/catch.
I also tried to exclude it by using fe:
if(elements.getName() == null)
Still, same results.
You don't need to use a parameterized type. Rather introduce a specific interface (for example NameAware) that exposes the getName() method that your classes with implement. In this way you could rely on a common type.
public interface NameAware{
String getName();
}
public class Resident implements NameAware{
...
public String getName(){
return name;
}
}
public class Furniture implements NameAware{
...
public String getName(){
return name;
}
}
And define your method as :
public static void printArrayList(ArrayList<NameAware> arrayToPrint) {
for (NameAware element : arrayToPrint) {
try {
System.out.println(element.getName());
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}
Note that you should change your actual code from :
ArrayList<Object> arrayList = new ArrayList<>();
to
ArrayList<NameAware> arrayList = new ArrayList<>();
The best practice would be to declare an interface with the getName method, and have both Furniture and Resident implement it.
public interface Namable {
public String getName();
}
Then, use a List<Namable> instead of a List<Object>:
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
List<Namable> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
for (Namable n : arrayList) {
System.out.println(n.getName());
}

Iterating over genric enum instance

As you can see below, I have three declared enums, and each class has a method called getEnumByName() which revives a name and returns the enum which has that name.
I have noticed that I am duplicating the same functionality of this method on each enum.
Is there any way to change this method to a generic one, which receives the given enum's type and does the same logic?
public class Enums {
public enum A {
APPLY("Apply", "abcde");
private String id;
private String name;
A(String name, String id) {
this.name = name;
this.id = id;
}
public static A getEnumByName(String name) throws Exception {
for (A instance : A.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
public enum B {
APPLY("Apply", "1"),
SAVE("Save", "2"),
REVERT("Revert", "2"),
REVERT_CHILD("Revert->Revert", "4"),
REVERT_APPLY("Revert->Revert Apply", "5"),
SYNC("Sync", "6"),
OPERATIONS("Operations", "7"),
IMPORT("Import", "8"),
EXPORT("Export", "9"),
DIFF("Diff", "10");
private String id;
private String name;
B(String name, String id) {
this.name = name;
this.id = id;
}
public static B getEnumByName(String name) throws Exception {
for (B instance : B.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
public enum C {
UPDATE_POLICES("Update Policies", "A"),
OPERATIONS("Operations", "B"),
IMPORT_CONFIGURATION_FILE("Import Configuration File", "c"),
EXPORT_CONFIGURATION_FILE("Export Configuration File", "d"),
EXPORT_LOG_SUPPORT_FILE("Export Log Support File", "f"),
EXPORT_TECHNICAL_SUPPORT_FILE("Export Technical Support File", "g"),
UPDATE_SOFTWARE_VERSION("Update Software Version", "g"),
UPDATE_SECURITY_SINGAUTES("Update Security Signatures", "h"),
DIFF("Diff", "k");
private String id;
private String name;
C(String name, String id) {
this.name = name;
this.id = id;
}
public static C getEnumByName(String name) throws Exception {
for (C instance : C.values()) {
if (instance.getName().equals(name)) return instance;
}
throw new Exception("There is no operations matches :" + name);
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
}
One option is to have them all implement a common interface called, say, Named:
interface Named {
String getName();
}
Now you can create a generic method like this:
static <E extends Enum<E> & Named> E getEnumByName(Class<E> enumClass, String name) throws Exception {
return Arrays.stream(enumClass.getEnumConstants())
.filter(e -> e.getName().equals(name))
.findAny()
.orElseThrow(() -> new Exception("There is no operations matches :" + name));
}
And call it like this:
A a = getEnumByName(A.class, "Apply");
Consider using the static Enum valueOf() method. You can call it generically as follows or just call it directly. See this answer for details.
static <E extends Enum<E>> E getEnumByName(Class<E> enumClass, String name) {
return Enum.valueOf(enumClass, name);
}

How to implement sort class

private class FileType extends Object {
private String Name;
private String Type;
public FileType() {
Name = null;
Type = null;
}
public void setFileType(String n, String t) {
Name = n;
Type = t;
}
public int compareTo(FileType ft) {
String decodedFileName = null;
String decodedInputName = null;
try {
decodedFileName = URLDecoder.decode(this.Name, "UTF-8");
decodedInputName = URLDecoder.decode(ft.Name, "UTF-8");
}
catch(UnsupportedEncodingException e) {
}
return decodedFileName.compareToIgnoreCase(decodedInputName);
}
}
Above code is my define class for file list.
I had implement compare file name.
The type may Folder or File.
But I want to sort file first priority is Type, and second priority is Name.
How can arrive it?
You have to implement Comparable / compareTo method.
Use Comparator Interface from java.util package to sort in more than one way......
Use the compare(T t1, T t2) method of Comparator
Eg:
Here is an example from site http://www.mkyong.com
import java.util.Comparator;
public class Fruit{
private String fruitName;
private String fruitDesc;
private int quantity;
public Fruit(String fruitName, String fruitDesc, int quantity) {
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public static Comparator<Fruit> FruitNameComparator
= new Comparator<Fruit>() {
public int compare(Fruit fruit1, Fruit fruit2) {
String fruitName1 = fruit1.getFruitName().toUpperCase();
String fruitName2 = fruit2.getFruitName().toUpperCase();
//ascending order
return fruitName1.compareTo(fruitName2);
//descending order
//return fruitName2.compareTo(fruitName1);
}
};
}
Compare both types. If the comparison is different from 0, return it as a result. If equal to 0, then compare the names.
Note that:
Extending Object is unnecessary: it's the default
Fields should start with a lower-case letter: name, type na dnot Name, Type
Your class should implement Comparable<FileType>
I would choose another name for the class: It's not a file type, but a file name associated to a file type
I would use an enum rather than a String for file types, since you only have two valid instances of file types
You should never ignore exceptions like you're doing. BTW, if this exception occurs, it could lead to a NullPointerException. Wrap the exception into a runtime exception and throw this runtime exception:
catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
Your compareTo method doesn't handle null names, although the default constructor assigns null to the name. Fix the method or the constructor. It seems to me that a file name should never be null, so I would fix the constructor.
if (this.Type.equals(ft.Type)){
return decodedFileName.compareTo(decodedInputName);
}
else{
return this.Type.compareTo(ft.Type);
}
You first compare the type and then the decoded name.
I cached the decodedFileName value directly in the class to prevent calling URLDecoder.decode too much.
private class FileType extends Object implements Comparable<FileType>{
private String name;
private String decodedFileName;
private String type;
public FileType(String n, String t) {
name = n;
try {
decodedFileName = URLDecoder.decode(this.name, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
type = t;
}
public int compareTo(FileType other) {
int result = type.compareToIgnoreCase(other.type);
if (result == 0){
result = decodedFileName.compareToIgnoreCase(other.decodedFileName);
}
return result;
}
}
if you have only two types, why dont make them enum?
then first you compare type.ordinal, if there are equal then compare names,
and also prevents from putting unwanted values there

Categories