Java helper class to dynamically create member variables and getter methods - java

I am trying to create a helper method that will take in the names (type String) of the member variables (could be any number of member variables) and automatically initialize/create the member variables as well as the getter methods. So I would call something like:
helperClass("hello", "myName", "is", "bob")
and the helperClass would look something like this:
public class helperClass {
helperClass(String ...a) {
for (String s: a)
//create member variables and getter methods dynamically
}
So, in the end, the caller of the function would have something like this:
public class helperClass {
private String hello
private String myName
private String is
private String bob
//getter methods below
...
}
Coming from Python so wasn't sure if this type of stuff is doable in Java.

Yes. You can create the getter and setter methods dynamically.
Tutorial for Java Dynamic POJO creation . But this method will involve you creating a predefined string which contains the method declaration.
Eg :
String s= "public void doSonething(String ... args){ // Function Body }" .
You can then convert this string into a function at runtime. Based on your need, you can define a custom string that contains the method declaration which you need. See some examples in the above tutorial link I have attached.

i think the answer is to use an IDE. They all have "add property" functions which will generate the declaration and appropriately named getters and setters.
Should you prefer to manually enter your properties, They all also have generate getter/setter functions which will look at the properties you have entered (work out which getters and setters are missing) and offer to create approporiately named getters and setters in bulk for the ones you've selected.
To answer your specific question, yes you can write your own class that takes a list of strings (i.e. property names) and print them out as a series of getters and setters, this is basic string concatenation:
private String generateGetter(String propName) {
return String.format(" public String get%s()\n return this.%s;\n }", StringUtils.capitalize(propName), propName);
}
To convert the first letter of the propName to upper case (the convention for getter and setter methods, you can do it yourself or use apache's string utils.

Related

Changing json to java pojo

Let's say I have a JSON file example.json
example.json
{
"BaggageMaxSize" : {
"mesurement" : "sum",
"width" : 70,
"height" : 50,
"depth" : 40
}
}
And create the POJO class:
public class pojoexample{
private BaggageMaxSize BaggageMaxSize;
// getter
// setter
}
And then:
public class BaggageMaxSize
{
private String height;
private String width;
private String depth;
private String mesurement;
// getter
// setter
}
Now, I want to use the mapper.readValue to change file to BaggageInfoPolicy.class:
BaggageInfoPolicy bip = mapper.readValue(file, BaggageInfoPolicy.class);
But bip.getBaggageMaxSize().getMesurement() returns null value. Any suggestions?
Try using mapper.writeValue first and check how your resulting JSON object will look like. Very likely, there's an issue with int -> string conversion in your BaggageMaxSize when deserialized from JSON.
Also, check your getters/setters to be publicly visible and be available both on pojoexample and BaggageMaxSize.
Actually your JSON represents a pojoexample class instance and not a BaggageInfoPolicy object, which you haven't shared in your post.
So you need to change your code to:
PojoExample bip = mapper.readValue(file, PojoExample.class);
So it reads the PojoExample object correctly.
Note:
Your class should follow the java naming convention and
start with an uppercase, that's why I changed it to PojoExample,
change it in the class definition as well.
And Make sure your class fields have the same types as in the JSON, and their getters and setters are correctly implemented.

How to create a java class with dynamic number of variables

I want to create a java class with dynamic number of variables. Those dynamic variables will be read from a config file.
Example: I have a properties file like,
{
"data": "int",
"name": "string",
"addr": "string",
"age" : "int"
}
In some cases, new variables can be there or few variables are missing from above config.
I want to create a java with variables mentioned in above properties file. Is it possible in java to create such class and if yes then can someone provide sample code for that?
Define a Map<String, String> that you can access by the key,
but why?
at the end all those "variables" will be the same type... -> String...
the same principe is done in config or property files....
I think you need to do a bit more research on java classes. There is no java class that has a dynamic "number" of variables. But you can give a class attributes, but require only some are set, for example.
class DataFile {
int data;
String name;
String addr;
int age;
}
And then you can create setters and getters for each field.
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
That way you can instantiate a member of the class and set the data you have.
DataFile d = new DataFile();
d.setName("John");
Remember that any class methods like setName and getName have to be inside the { } that define the class to which they belong. They aren't here just to separate them visually.
All of that already exists. It is called "Properties" in Java, too.
So, simply read about them here!
In other words: you could/should use java.util.Properties; and there is full support for reading that information from files; or writing to.
The Java property file format does not match your current file format; but well, when you are doing "true" Java, then the most "off the shelf" solution are Java properties; so so you could consider to change your file format.
And to give the actual answer: Java does not support a dynamic number of fields. That is what Maps are used for; and the Property class is exactly that - some sort of Map with additional functionality.
How about something like this
public class Model {
Map model;
public Model(String json) {
model = new Gson().fromJson(jsonModel, Map.class);
}
public Object getValue(String key) {
return model.get(key);
}
}
But you'd rather want your model to hold data for values, leaving the type inference of the fields to Java.

How to set and get values from an Object that exists in an ArrayList<Verbs>

I'm trying to make an array of objects called Verbs.
The Verb class has 4 Strings.
public class Verb {
String maori;
String englishPast;
String englishPresent;
String englishFuture;
}
Do I need to write get and set methods into this class in order to change these values or does android handle it for you somehow?
This seems to not be an Android problem but a java related question. You should create a Verb class like this:
public class Verb {
private String maori;
//All other strings you need
public String getMaori() {
return maori;
}
//Add a setter as well
Then you should create your Verb objects and add these objects to your array. But this has nothing to do with Android at all!

Eclipse, short way to initialize object via setters

For example I have the following object:
public class Dog{
private String name;
private int age;
private int legs;
private Color color;
/*getters and setters*/
}
And I want to initialize it and set all properties not by constructor but by using setters:
Dog dog = new Dog();
dog.setName("Rex");;
dog.setAge(4);
...
Can I generate code which set all fields from above in the easy way?
It's cumbersome, but what I do:
Use Eclipse's Source -> Generate Getters and Setters... function (also ALT + SHIFT + S) and then just replace all '=' characters with '(' and ';' with ');'. finally I go through every line and press ctrl-space to let Eclipse finish the method call with proper casing (configure Eclipse to overwrite instead of insert code assist suggestions).
That or do a regex replacement if it is a lot.
You can introduce a setAllValues method, that should take all the attributes of your class as parameters. And simply call the setters inside that method.
You can create a new template in eclipse in Preferences/Java/Editor/Templates and then just use it (similar to 'syso' ctrl+space that produces System.out.println)

how find fields of all member variables contained in java bean

I want to make a GUI using Java in which a user can select a bean, edit its fields, and then add an instance of the created bean to a queue. My question though is about accessing the fields. I have a class MyCompositeObject that inherits from MyParentObject. The MyParentObject is composed of multiple beans, each being composed of more beans. The class MyCompositeObject is also composed of beans. I want to find all accessible fields from MyCompositeObject.
Class MyParentObject
{
MyObjectOne fieldOne;
MyObjectTwo fieldTwo;
String name;
...
}
Class MyCompositeObject extends MyParentObject
{
MyObjectThree fieldThree;
Integer number;
...
}
Class MyObjectThree
{
boolean aBoolean;
MyObjectFour fieldFour;
...
}
I have been trying to use the BeanUtils api, but I'm getting stuck trying to get the fields of all the member beans. What I am imagining is a depth first search of all fields that could be accessed from an instance of MyCompositeObject. For example, this would include, but not be limited to, the fields: MyCompositeObject.fieldOne, MyCompositeObject.number, MyCompositeObject.fieldThree.aBoolean.
I realized when I tried:
Fields[] allFields = BeanUtils.getFields(myCompositeObject);
that I was in over my head. My research has so far not turned up any prebuilt methods that could do what I describe. Please let me know of any API methods that can do this or tell me how I can go about building my own. Thanks.
It's kind of a pain but you have to go in two dimensions
yourBeanClass.getSuperclass(); (and recursively get all superclasses until Object)
and then you can get the fields of each one
eachClass.getDeclaredFields() NOT getFields so you can get all the private fields
Once you have each field
field.getType() which returns the Class of that field
then of course, you need to go up that dudes superclass chain again to make sure you get ALL the fields of the class including the ones in the superclass
Once you have that chain of classes for that field, you can then get it's fields by repeating the above....yes, the jdk made this fun!!!! I wish to god they had a getAllDeclaredFields method so I didn't have to go up the superclass heirarchy.
IMPORTANT: you need to call field.setAccessible(true) so you can read and write to it when it is a private field by the way!!!
Here is code that gets all the fields for a Class including the superclasses..
private static List<Field> findAllFields(Class<?> metaClass) {
List<Field[]> fields = new ArrayList<Field[]>();
findFields(metaClass, fields);
List<Field> allFields = new ArrayList<Field>();
for(Field[] f : fields) {
List<Field> asList = Arrays.asList(f);
allFields.addAll(asList);
}
return allFields;
}
private static void findFields(Class metaClass2, List<Field[]> fields) {
Class next = metaClass2;
while(true) {
Field[] f = next.getDeclaredFields();
fields.add(f);
next = next.getSuperclass();
if(next.equals(Object.class))
return;
}
}
later,
Dean

Categories

Resources