I have to convert result of a LazyDynaBean class to MyCustom class. Whats the best way to convert result from LazyDynaBean , I see a way through BeanUtil class but its is not converting any of my own type of classes,
My Custom Class is like
public class Xyz {
String name;
Point point;
}
public class point {
int x;
int y;
}
If your problem is with nested classes (beans with properties that are in turn beans) you're out of luck with using BeanUtilsBean.copyProperties(). The JavaDoc does mention that it's intended for "shallow copying" only.
What you'll have to do is write your own "Converter" class to handle the conversion of the nested bean variable classes and stitch it all together yourself.
If you keep your top level bean limited on its use of non-bean member variables (i.e. push them down into another bean if there are many), your conversion code will at least be able to use BeanUtilsBean.copyProperties() for those beans that are "shallow".
Related
Sorry if this question is too specific but I can't seem to think of the right terminology to explain it in an abstract way.
I have two classes for the same entity. One for saving it to the database
public class XDb extends SugarRecord {
private float ampX;
private float ampY;
}
and the other for Api calls:
public class XApi extends ApiFunctionality {
private float ampX;
private float ampY;
}
I first save the objects in the local database, then I read from the database and upload data to the server.
I want to be able to do something like this:
XApi xApi = (XApi) xDb;
Is there any functionality in java that supports this?
Apologies if I am still ambiguous.
In a word, no. You can't. They have to have some relationship. They could both implement a common interface, for example.
You cannot cast them, since the types are unrelated.
Assuming that you have:
Appropriate accessors (e.g. getAmpX() and getAmpY(), or non-private visibility of ampX and ampY - not recommended) on the class that you want to convert from (XDb in your example);
An appropriate constructor on the class that you want to convert to (XApi in your example)
then you can simply construct an instance of the latter using the properties of the former:
XApi xApi = new XApi(xDb.getAmpX(), xDb.getAmpY());
They must be of the same hierarchy tree,
if XApi inherits (extends) XDb, you will be able to cast.
I have
class A
{
String a;
String b;
//..getters, setters
}
Now I have ArrayList<? extends Object> resultData holding objects of class A and some other classes.
Basically I need this list 'resultData' to generate a Json file in some other API.
Now my question is while adding the class A objects to the list & some condition(X) is true I need a modified class A object (or any other anonymous class object) like:
class A
{
String a;
//..getters, setters
}
that is one particular object of class A shouldn't have field String b (before criticising, I'm doing this because I need such modified object for my particular JSon format & I don't want to define a new class definition that is used only once)
my last option is to make anonymous class like this: (& then add it to my List)
Object ob = new Object{
String b;
//..getters, setters
}
Also pls. suggest any other method of creating anonymous class with required structure.
Java is not meant for changing classes or creating new classes at runtime.
It is possible with a lot of effort, like generating java bytecode on the fly using a bytecode library like BCEL(http://commons.apache.org/proper/commons-bcel/) or even generate .java files and run javac to generate bytecode.
You could simply use a hash map like Map<String,Object> that "simulates" an object that can receive arbitrary fields. If you really need totally configurable classes, I would go this way. Of course, you would not have nice getters and setters for each property.
But why would you need nice setters / a nice class anyway? As the structure of the class is determined at runtime, you can write no code that depends on this class, as you do not know how it will look like.
if i'm getting you correctly, you need to get rid off field for serialization, to json format,
if im right, then make your field transient
other solution is to make super class with field which you want to serialize,
and make A to extend it
but modifying class on fly, it is not right way to go
I was reading about Java beans, and all the examples I came across use standard Java types (String, int, etc) for class variables. Can I use variables of my own class type in a bean?
Eg.
class MyBean implements java.io.Serializable{
MyObj mo;
public MyBean(){}
//Getter and setter for mo
}
(Writing this from a phone, so apologize for no formatting)
Yes, you can.
You can implement your own business logic using POJO defined by yourself plugging reusable components as well.
If you use JSF remember to create setter and getter for your variables if you want to access them from your JSP/Facelets pages. The naming convention is pretty standard, if you have a String named 'foo' the framework will call the
public String getFoo()
{
return foo;
}
method.
I have been challenged by a design issue which I will try to describe below.
Suppose that a class, call it A, has a constructor with a bunch of parameters. Since it is tiring and dirty to write all those parameters in each instantiation, I have written another class, call it StyleSheetA, which encapsulates all those parameters and is the only parameter to the constructor of A. In this way, I can prepare some default StyleSheetA templates to be used later, and if it is needed, I can modify them.
And at this point, I need to extend A. Suppose B extends A. B will have its own stylesheet, namely StyleSheetB. I think it will be appropriate that StyleSheetB extends StyleSheetA, so with one stylesheet parameter, constructor of B can also construct its super class A. But I am afraid of the possibility that this design may have flaws. For example what if I decide to add a getter/setter for the stylesheet? Is there a novel way to handle all these situations? Am I in the wrong way? For those who are confused, I attach some code here:
class A
{
StyleSheetA ss;
A(StyleSheetA ss)
{
this.ss = ss;
// Do some stuff with ingredients of styleSheet
}
}
class StyleSheetA
{
int n1;
int n2;
// :
// :
int n100;
}
class B extends A
{
B(StyleSheetB ss)
{
super(ss);
// Do some stuff with ingredients of styleSheet
}
}
class StyleSheetB extends StyleSheetA
{
int n101;
int n102;
// :
// :
int n200;
}
Thank you for any help or suggestions, also any of your critics will be appreciated.
Edit: I am developing in java me so there is no generics support.
It seems to me that you are only moving the problem of having too many parameters from class A to class StyleSheetA.
To illustrate my point, think of this question: How would you instantiate StyleSheetA? Probably using a constructor that accepts all these parameters, anyway. The only benefit this design may give you is if you have a same set of parameter values encapsulated by an object of StyleSheetA which you will reuse among multiple instances of A. If so, bear in mind that although you'd have different instances of A they would share the same parameters, so it isn't a good choice.
What I could recommend you is to try to refactor your class A itself. Try to break it up into smaller classes. If nesseccary, try to create subclasses to avoid conditional branches, etc.
Now, I don't know how your class A looks like, but maybe if you do so you'll have several classes, each with its own set of parameters. And if any of the parameters is a discriminator (meaning that it determines the class "type") you will be able to get rid of it, just by using subclasses, and relying on built in type system to do it instead.
Have you considered using an IoC container, like StructureMap, to manage your constructor dependencies? That might make a lot of this stuff easier.
A thoughts on the getter and setter issue:
The constructor in 'B' implies that the additional parameters (n101+) are necessary for the operation of the class. If you were just extending the class with a full parameter list, you would have getters and setters for n101...n200 in B and n1...n100 in A. This suggests perhaps not having StylesheetB extend StylesheetA, but rather have the constructor to class B be B(StyleSheetA,StyleSheetB), this way you can have a setter in class A for it's parameters, have that inherited and also put one in B for StylesheetB.
I have a Java class with ~90 fields. I want to be able to do things to every field (generate an XML element for instance) without writing the same 5 lines of code with slight substitutions 90 times. In Objective C I think you can get to instance variables in ways similar to accessing Dictionary elements (ObjectForKey). Is there anything similar in Java such that I can get an array of the fields then do something to each of them?
Yes, it's called Reflection API.
In particular, MyClass.class.getDeclaredFields() will return a full list of fields declared by this class (see API for details)
Here's another approach: Use the Introspector API with the JDK to obtain bean-like properties of a class. This is helpful if you have getters and setters for your class and do not want to access the private fields directly.
Obtain a BeanInfo via the Introspector and get all the propertyDescriptors from it. To find getter of that property.
I'll have to admit that using this API is a bit cumbersome and reflection (suggested by Nikita Rybak) is more straight forward.
But there's a utility Apache BeanUtils that does all the hardwork internally so working with beans becomes simple.
Add:
If you are using the reflection API, I'd suggest you annotate your bean fields or your getters with a custom annotation.
public class MyClassWith90Fields {
#XmlSerialize("name")
private String screenName; // shoudl serialize as <name>...</name>
#XmlSerialize
private String email; // shoud serialize as <email>...</email>
#XmlSerializeIgnore
pirvate boolean flag; // shoud not serialize as annotated as ignore
}
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD, ElementType.METHOD})
public #annotation XmlSerialize {
public String value;
}
Once done, your generation code can check (using reflection) annotated fields and serialize them to XML appropriately.