I have a very simple problem-
I have a class named DEClient whose constructor is like this-
public DEClient(List<DEKey> keys) {
process(keys);
}
And DEKey class is like this-
public class DEKey {
private String name;
private String value;
public DEKey(){
name = null;
value = null;
}
public DEKey(String name, String value){
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Now I am trying to instantiate DEClient constructor. So for that I need to have List<DEKey>.
So what I did is I instantiated DEKey class like below using service.getKeys() (which will return String) and id as the value.
DEKey dk = new DEKey(service.getKeys(), id);
//The below line throws exception whenever I am running.
DEClient deClient = new DEClient((List<DEKey>) dk);
What wrong I am doing here?
You need to first make a List, then add your key to that List. Casting like you have done is not the way to do it, since DEKey is not a List and casting into it will throw a ClassCastException.
DEKey dk = new DEKey(service.getKeys(), id);
List<DEKey> list = new ArrayList<DEKey>();
list.add (dk);
DEClient deClient = new DEClient(list);
Related
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.
I have a CustomObject declared as raw type of <T>. And when I populate a List<CustomObject> with new instances of it, I can't get them back as a CustomObject, only as an Object.
public class CustomObject<T> {
private String name;
private T value;
// getters and setters
}
But obviously when I use subclass, all is working as expecting;
public class CustomObject {
private class SubCustomObject<T> {
private String name;
private T value;
}
public CustomObject() {
this.customObject = new SubCustomObject();
private SubCustomObject customObject;
// getters and setters
}
Is there a way to make the first example to behave like the second one, and avoid using extra object and so I could do this:
public class CustomObject<T> {
private String name;
private T value;
private boolean isGroup;
// getters and setters
private void setValue(T value) {
if (value instanceof String) {
this.value = value;
this.isGroup = false;
}
if (value instanceof CustomObject) {
if (isGroup()) {
((List<CustomObject>) this.value).add((CustomObject) value);
} else {
this.value = (T) new ArrayList<CustomObject>();
this.isGroup = true;
setValue(value);
}
}
}
}
public void getItemByName(String name) {
// say the list is already populated
for (CustomObject object : listOfCustomObject) {
String nameField = object.getName();
if (name.equals(nameField) {
System.out.println(nameField);
}
}
}
Instead of this one:
public void getItemByName(String name) {
// say the list is already populated
for (Object object : listOfCustomObject) {
String nameField = ((CustomObject)object).getName();
if (name.equals(nameField) {
System.out.println(nameField);
}
}
}
// Apply that behavior to this and avoid to use inner class.
public class MetadataEntry {
public MetadataEntry() {
this.entity = new Entry();
}
private class Entry<T> {
private String name;
private T value;
private boolean isGroup;
private void setValue(T value) {
if (value instanceof String) {
this.value = value;
this.isGroup = false;
}
if (value instanceof MetadataEntry) {
if (isGroup()) {
((List<MetadataEntry>) this.value).add((MetadataEntry) value);
} else {
this.value = (T) new ArrayList<MetadataEntry>();
this.isGroup = true;
setValue(value);
}
}
}
}
private Entry entity;
public void setName(String name) {
this.entity.name = name;
}
public String getName() {
return this.entity.name;
}
public void setValue(String value) {
entity.setValue(value);
}
public void setValue(MetadataEntry value) {
entity.setValue(value);
}
public boolean isGroup() {
return this.entity.isGroup;
}
public List<MetadataEntity> getChildNodes() {
if (isGroup()) {
return (List<MetadataEntry>) this.entity.value;
}
return null;
}
public String getValue() {
if (!isGroup()) {
return (String) this.entity.value;
}
return null;
}
}
You can not make a list of different types X,Y,Z and put it in a single container of type W. You need to define a bounding parameter on your raw type so that your items and list are of same type. probably your T should be bounded by some interface type or it should extends some class.
Here’s my suggestion. I have abandoned the generics. Instead of just one inner class there is now an abstract inner class with two subclasses, one for groups and one for entries that are not groups. The good news: no cast is necessary anywhere.
public class MetadataEntry {
private String name;
static abstract class Entry {
abstract Entry setValue(String value);
abstract Entry setValue(MetadataEntry value);
abstract boolean isGroup();
abstract List<MetadataEntry> getChildNodes();
abstract String getSimpleValue();
}
static class SimpleEntry extends Entry {
private String value;
public SimpleEntry(String value) {
this.value = value;
}
#Override
Entry setValue(String value) {
this.value = value;
return this;
}
#Override
Entry setValue(MetadataEntry value) {
return new GroupEntry(value);
}
#Override
public boolean isGroup() {
return false;
}
#Override
public List<MetadataEntry> getChildNodes() {
return null;
}
#Override
public String getSimpleValue() {
return value;
}
}
static class GroupEntry extends Entry {
List<MetadataEntry> value;
public GroupEntry(MetadataEntry value) {
this.value = new ArrayList<>();
this.value.add(value);
}
#Override
Entry setValue(String value) {
return new SimpleEntry(value);
}
#Override
Entry setValue(MetadataEntry value) {
this.value.add(value);
return this;
}
#Override
public boolean isGroup() {
return true;
}
#Override
public List<MetadataEntry> getChildNodes() {
return value;
}
#Override
public String getSimpleValue() {
return null;
}
}
private Entry entity;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setValue(String value) {
entity = entity.setValue(value);
}
public void setValue(MetadataEntry value) {
entity = entity.setValue(value);
}
public boolean isGroup() {
return this.entity.isGroup();
}
public List<MetadataEntry> getChildNodes() {
return entity.getChildNodes();
}
public String getValue() {
return entity.getSimpleValue();
}
}
I have used an idea similar to what m 1987 said about a class that returns an instance of itself. I applied it to the inner classes only to free the users of the outer class from caring about this trickery. If you prefer, I am sure it could be applied to the outer class instead. Then you would have an abstrat class on the outer level with two subclasses, and would no longer need the inner classes. This is one of the things you asked for, so you may prefer it, but it comes at a cost: anyone calling setValue() on the outer class would need to remember that they got a new instance back.
I have a CustomObject declared as raw type of <T>.
That doesn't makes sense. You either have a raw type or a generic, not a raw type of a generic.
And when I populate a List with new instances of it, I can't get them back as a CustomObject, only as an Object.
Because your list is not generic (always bad). When you declare a List<Something> it will return Something on a get call. That Something can be generic or a raw type. A List<CustomObject<String>> will not accept a CustomObject<Integer> and using the raw type List<CustomObject> will end in disaster, hence the danger in raw types.
Now let's look at your code. The class
public class CustomObject<T> {
private String name;
private T value;
}
defines an object that behaves the same for any type. In essence what you have here is just a glorified Object with a String serving as its name attached to it.
However, now you do
private void setValue(T value) {
if (value instanceof String)
// ...
if (value instanceof CustomObject)
// ...
}
which separates the behavior for different types. and what happens if the generic type is not a String or a CustomObject?
Let's try to solve your problem. Since generics are meant to unify the behavior, let's look at what the unified behavior is that you're trying to get:
public void getItemByName(String name) {
for (CustomObject object : listOfCustomObject) {
String nameField = object.getName();
// ...
}
}
}
Basically, you require that all the items in listOfCustomObject implement a String getName() method. That's it as far as I can see from your question. That means that your CustomObject<T> should either implement an interface or extend a class (call it Superthing) with that method. Then you will just declare your list as List<? extends Superthing>.
As for the CustomObject itself, it doesn't need to be generic as you hint that there are only 2 types of generics you want to deal with (you have 2 ifs, but no else to deal with a general case). It looks like what you want are 2 different classes with different behaviors that both implement or extend a common supertype.
Try something like this:
abstract class AbstractEntry {
private String name;
protected boolean isGroup;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isGroup() {
return isGroup;
}
}
class MetaEntry extends AbstractEntry {
AbstractEntry value;
MetaEntry(AbstractEntry value) {
this.value = value;
// handle isGroup
}
public void setValue(AbstractEntry value) {
this.value = value;
}
public AbstractEntry getValue() {
if (!isGroup)
return value;
return null;
}
}
class StringEntry extends AbstractEntry {
String value;
StringEntry(String value) {
this.value = value;
isGroup = false;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
I think there is no need of list as it always hold only one element. As #Ole V.V mentioned, the requirement naturally calls for the use of composition and in fact, generic does not fit into your requirements. Here is how I would tackle your requirements:
public interface Named {
public String getName();
public String getValue();
}
public class CustomObject implements Named {
private String name;
private String value;
private boolean isGroup;
// getters and setters
private boolean isGroup() {
return isGroup;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class CustomObject2 implements Named {
private String name;
private CustomObject value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value.getValue();
}
public void setValue(CustomObject value) {
this.value = value;
}
}
public class DriverCustomObject {
public static void main(String arg[]) {
CustomObject t = new CustomObject();
t.setName("key1");
t.setValue("value1");
CustomObject2 t2 = new CustomObject2();
t2.setName("complex");
t2.setValue(t);
List<Named> list = new ArrayList<Named>();
list.add(t);
list.add(t2);
for (Named l : list) {
System.out.println(l.getName());
System.out.println(l.getValue());
}
}
}
I am stumped with this one and hoping to see if this could be a good way to solve my issue.
I'll first explain how the program works.
I have a class that is simply a key value pair:
public class KeyValuePair {
private final String name;
private final String value;
public KeyValuePair(String n, String v) {
name = n;
value = v;
}
I have another class called List that uses the key value pair.
public class myList {
private List<KeyValuePair> myList = new ArrayList<KeyValuePair>();
public myList(List<KeyValuePair> nvp) {
List = nvp;
}
public List<KeyValuePair> getList() {
return myList;
}
}
So in my program i then create an List object and populate it with the key value pairs and review a new List(kvp).
public myList pullData(){
Final myList<KeyValuePair> nvp = new ArrayList<KeyValuePair>();
List<String[]> results = getResults()
for(String[] str : results)
{
KeyValuePair kvp = new KeyValuePair(str[0], str[1]);
nvp.add(kvp)
}
}
return new myList(nvp)
}
now I have run into the situation where I need to update the value of each pair. The key stays the same.
Originally I had created a newList object and populated with the updated Value for the key pair, but then though there should be a better method, perhaps creating an update or a setter method within the List object to do this.
Which would be better creating a new object, or updating? I would think updating the value in the key value pair, however, I am not sure how to do this.
Any help or suggestions would be greatly appreciated.
Then you can set the keys and values if you want:
public class KeyValuePair {
private String name;
private String value;
public KeyValuePair(String n, String v) {
name = n;
value = v;
}
public String getName(){
return name;
}
public String getValue(){
return value;
}
public void setName(String n){
name = n;
}
public void setValue(String v){
value = v;
}
}
However a list of these is never going to be as useful as a map that is already there in Java.
Lose final modifier and create nice getters and setters for your fields
public class KeyValuePair {
private String name;
private String value;
public KeyValuePair(String n, String v) {
name = n;
value = v;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
and then you can e.g. add plus sign to your values:
public void update(List<KeyValuePair> pairs) {
for (KeyValuePair kvp: pairs) {
kvp.setValue(kvp.getValue() + "+");
}
}
Simply by adding a setter to my key value pair class resolved this issue. Not too sure why i didn't see that before, for some reason I thought I needed to do it in myList class.
public void setValue (String newValue){
value = newValue;
}
i have a Java Enum like below
public enum TestEnum{
{
A("a","b","c"),
B("a1","b1","c1"),
C("a2","b2","c2");
TestEnum(String a,String b,String c){
}
private String a;
private String b;
private String c;
}
I want to externalize this config to an XML file but XSDs donot seem to support attributes on Enum Element type. Is there a way to work this around or an alternate to it.
You could do something like this (even though for enum, this looks too verbose)
#XmlJavaTypeAdapter(CountXmlAdapter.class)
public enum Count {
ONE(1, "one"),
TWO(2, "two"),
THREE(3, "three");
private final int index;
private final String name;
private Count(int index, String name) {
this.index = index;
this.name = name;
}
#XmlAccessorType(XmlAccessType.FIELD)
public static class CountWrapper {
private int index;
private String name;
public CountWrapper() {
}
public CountWrapper(int index, String name) {
this.index = index;
this.name = name;
}
}
public static class CountXmlAdapter extends XmlAdapter<CountWrapper, Count> {
#Override
public Count unmarshal(CountWrapper v) throws Exception {
return v != null ? Count.valueOf(v.name.toUpperCase()) : null;
}
#Override
public CountWrapper marshal(Count v) throws Exception {
return v != null ? new CountWrapper(v.index, v.name) : null;
}
}
}
I am trying to write my own bean utils converter so that I can export my object to a plain text file
I have the main class
public class BeanUtilsTest {
public static void main(String[] args) {
try{
MyObject myObject = new MyObject();
myObject.setId(3l);
myObject.setName("My Name");
ConvertUtilsBean cub = new ConvertUtilsBean();
cub.deregister(String.class);
cub.register(new MyStringConverter(), String.class);
cub.deregister(Long.class);
cub.register(new MyLongConverter(), Long.class);
System.out.println(cub.lookup(String.class));
System.out.println(cub.lookup(Long.class));
BeanUtilsBean bub = new BeanUtilsBean(cub, new PropertyUtilsBean());
String name = bub.getProperty(myObject, "name");
System.out.println(name);
String id = bub.getProperty(myObject, "id");
System.out.println(id);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
The Long Converter
public class MyLongConverter implements Converter{
#Override
public Object convert(Class clazz, Object value) {
System.out.println("Long convert");
return value.toString()+"l";
}
}
The String Converter
public class MyStringConverter implements Converter{
#Override
public Object convert(Class clazz, Object value) {
System.out.println("String convert");
return value.toString()+":";
}
}
Finally my object
public class MyObject {
Long id;
String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The Output
String convert
My Name:
String convert
3:
I was expecting the id will go through MyLongConverter, but it seems it is still going thru the String one. Why and how can I fix this?
Please advise
Thanks
String id = bub.getProperty(myObject, "id");
Above getProperty function in BeanUtilBean class has to return String representation of the property you requested, regardless of what format the property is defined. So, it will always use String converter (MyStringConverter).
Since the destination type here is always String, MyLongConverter will never be used.
Instead, MyStringConverter should inspect the type of the value parameter and accordingly convert it to String.