更通用的回报 [英] A more generic return
问题描述
让一个类有一些私有变量,例如:
myBool1,myBool2,myBool3
myInt1,myInt2,myInt3
myString1,myString2,myString3
执行通用于返回值的getter函数的最佳方法是什么?因此,如果我使用类似以下方式对getter进行调用:
myNewBool =< blah> .get(myBool1)
myNewString =< blah> .get(myString2)
myNewInt =< blah> .get(myInt3)
任何人有任何建议?
如果您不知道要获取什么,则无法真正拥有通用getter,例如:
boolean myNewBool = get(myString1);
如果 get
返回一些内容,真的不知道这是否与布尔值兼容,并且可能会发生可怕的事情。
您可以试试这个:
public< T> get(String element){
return(T)elementToGet;
}
但是当你调用get方法时你必须指定返回类型。
String element = myObject。< String> get(element);
以下是不好的一面: 您可以改为使用旧的getter // setter,如果有使用IDE来生成它们。 另一种方法是使用lombok项目。 资源: 关于同一主题:
get
方法中输入一个非常长(和臭的)代码来使用每个可能的属性(如果你仍然想要一些私有的并且不可访问的)或更糟的是,使用反射来找到正确的属性。
Looking at some code cleanup and I was wondering the best way to deal with this:
Have a class with some private variables like:
myBool1, myBool2, myBool3
myInt1, myInt2, myInt3
myString1, myString2, myString3
What's the best way to do a getter function that is generic to the return value? So if I do a call to the getter with something like:
myNewBool=<blah>.get("myBool1")
myNewString=<blah>.get("myString2")
myNewInt=<blah>.get("myInt3")
Anyone have any suggestions?
You can't really have a generic getter if you don't know what you want to get, for example :
boolean myNewBool= get("myString1");
If get
returns something, but you don't really know if this something is compatible with a boolean, and terrible things could happen.
You could try this:
public <T> get(String element){
return (T) elementToGet;
}
But you would have to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides :
- You can't work directly with primitives
- You can have a lot of ClassCastException
- If you misspell an attribute name you won't see it until you run it
- You don't expose a nice public API, people would have to know evert possible attribute to use it, and as said above, a misspelled attribute (or an inexistant one) wouldn't be seen until runtime.
- You have to know the return time and type it each time you use your method
- You would have to type a really long (and smelly) code in your
get
method either to use each possible attribute (if you still want have some private and not accessible) or worse, use reflection to find the right attribute.
So definitively not a good idea.
What you can do instead is using the good old getters//setters and if there is a lot of them, generate them with your IDE.
Another way would be to use the project lombok.
Resources :
On the same topic :
- Create automatically only getters in Eclipse
- Eclipse Generate All getters setters in package
- Java Getters and Setters
这篇关于更通用的回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!