How to dynamically generate a Java Bean class using plain Java? - java

I went through some of the samples that have used libraries to generate bean classes from JSON, XML etc. What I would like to know is, whether there's a way to dynamically generate a java bean class, with the parameters I give?
For example if I give an array of Strings as arguments which would represent the properties of the Pojo class for now, how can I generate the POJO?
Arguments: {"field1", "field2", "field3"}
Generate POJO would be:
public class TestBean {
private String field1;
TestBean() {
}
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
}
It should be the same for field2 and field3 as well.
Here I'm assuming that all the properties above are String and the class name is constant for now. Is there any way I can achieve this? Thanks in advance.

The problem with generating an actual Java class at runtime is that there is no way you can access it using standard Java syntax as the compiler doesn't know about it.
In practice therefore, most people just use a map in this circumstance. The only case I can think where you would need to generate a real class is where there is some other code you can't change that requires a Java object and inspects it dynamically using reflection or otherwise.
If you don't need this you are better off using a map, or possibly some utility class designed to emulate a Java Bean.
The Apache BeanUtils package provides the DynaBean interface to implement dynamic Java Beans. That said, the classes are only recognised as beans if accessed from the rest of the BeanUtils package.
There are several subclasses depending on what you want, for example, LazyDynaBean:
DynaBean myBean = new LazyDynaBean();
myBean.set("myProperty", "myValue");

Related

Is there a way to completely swap out the way serialization is handled with Apache Beam?

I'm using Kotlin with Apache Beam and I have a set of DTOs that reference each other and all serialize great for any encoder with Kotlinx Serialization. When I try to use them with Beam I end up having issues because it's looking for all objects, type parameters and nested objects to implement the Java Serializable interface. Problem is, I'm not in control of that with all object types because some come from 3rd-party libraries.
I've implemented my own CustomCoder<T> type that uses Kotlinx Serialization but then I run into issues with my custom coder not being serializable, particularly due to the Kotlinx Serialization plugin-generated Companion object serializer not serializing. Since it's compile-time generated code I don't really have control over that and I can't flag it as #Transient. I tried implementing Externalizable on the coder and it fails as soon as I pass a type argument for T that doesn't implement Serializable or has a nested type argument that doesn't.
Also, Kotlinx Serialization is nice because it doesn't use reflection. It would make a lot of my current headaches disappear if I could just swap out the serialization mechanism somehow and not have to rely on standard Java serialization methods at all or somehow implement Externalizable in a way that just calls out to my own serialization mechanism and ignores the type parameter. Are there any solutions? I don't care how hacky it is, even if the solution involves messing with stuff in the Gradle build config to override something. I'm just not sure how to go about it so any pointers would be a great help!
Alternatively, if I abandon Kotlinx Serialization, are there any simple solutions to make any arbitrarily complex data type serialization just work with Java, even using reflection, without a lot of custom, manual work to handle encoding and decoding? I feel like maybe I'm just missing something obvious. This is my first project with Apache Beam but so far the google is little help.
Mybe late, I develop an annotation processor called beanknife recently, it support generate DTO from any class. You need config by annotation. But you don't need change the original class. This library support configuring on a separate class. Of course you can choose which property you want and which you not need. And you can add new property by the static method in the config class. The most power feature of this library is it support automatically convert a object property to the DTO version. for example
class Pojo1 {
String a;
Pojo b; // circular reference to Pojo2
}
class Pojo2 {
Pojo1 a;
List<Pojo1> b;
Map<List<Pojo1>>[] c;
}
// remove the circular reference in the DTO
#ViewOf(value = Pojo1.class, includePattern = ".*", excludes={Pojo1Meta.b})
class ConfigureOfPojo2 {}
// use the no circular reference versioned dto replace the Pojo1
#ViewOf(value = Pojo2.class, includePattern = ".*")
class ConfigureOfPojo2 {
// convert b to dto version
#OverrideViewProperty(Pojo2Meta.b)
private List<Pojo1View> b;
// convert c to dto version
#OverrideViewProperty(Pojo2Meta.c)
private Map<List<Pojo1View>>[] c;
}
will generate
// meta class, you can use it to reference the property name in a safe way.
class Pojo1Meta {
public final String a = "a";
public final String b = "b";
}
// generated DTO class. The actual one will be more complicate, there are many other method.
class Pojo1View {
private String a;
public Pojo1View read(Pojo1 source) { ... }
... getters and setters ...
}
class Pojo2Meta {
public final String a = "a";
public final String b = "b";
public final String c = "c";
}
class Pojo2View {
private String a;
private List<Pojo1View> b;
private Map<List<Pojo1View>>[] c;
public Pojo1View read(Pojo2 source) { ... }
... getters and setters ...
}
The interest things here is you can safely use the class not exist yet in the source. Although the compiler may complain, all will be ok after compiled. Because all the extra class will be automatically generated just before compiled.
A better approach may be to compile step by step, first add #ViewOf annotations, and then compile, so that all the classes that need to be used later are generated. Compile again after the configuration is complete. The advantage of this is that the IDE will not have grammatical error prompts, and can make better use of the IDE's auto-complete function.
With the support of using generated DTO in the configure class. You can define a Dto without circular reference just like the example. Furthermore, you can define another dto for Pojo2, and remove all property reference the Pojo1 and use it to replace the property b in Pojo1.

Efficient Java Annotations

I'm a huge fan of Java's annotations, but find it a pain in the neck to have to include Google's Reflections or Scannotations every time I want to make my own.
I haven't been able to find any documentation about Java being able to automatically scan for annotations & use them appropriately, without the help of a container or alike.
Question: Have I missed something fundamental about Java, or were annotations always designed such that manual scanning & checking is required? Is there some built-in way of handling annotations?
To clarify further
I'd like to be able to approach annotations in Java a little more programatically. For instance, say you wanted to build a List of Cars. To do this, you annotate the list with a class that can populate the list for you. For instance:
#CarMaker
List<Car> cars = new List<Car>();
In this example, the CarMaker annotation is approached by Java, who strikes a deal and asks them how many cars they want to provide. It's up to the CarMaker annotation/class to then provide them with a list of which cars to include. This could be all classes with #CarType annotations, and a Car interface.
Another way of looking at it, is that if you know you want to build something like this: List<Car> cars, you could annotate it with #ListMaker<Car>. The ListMaker is something built into Java. It looks for all classes annotated with #CarType, and populates the list accordingly.
You can create your own annotations and apply them to your own classes.
If you specify that an annotation is detectable at runtime, you can process it easily with reflection.
For example, you could use something like this to print the name of each field in a class that has been marked with the Funky annotation:
for (Field someField : AnnotatedClass.getClass().getDeclaredFields()) {
if (someField.isAnnotationPresent(Funky.class)) {
System.out.println("This field is funky: " + someField.getName());
}
}
The code to declare the Funky annotation would look something like this:
package org.foo.annotations;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Funky { }
Here's a class that uses the annotation:
package org.foo.examples;
import org.foo.annotations.Funky;
public class AnnotatedClass {
#Funky
private String funkyString;
private String nonFunkyString;
#Funky
private Integer funkyInteger;
private Integer nonFunkyInteger;
}
Here's some more reading on Annotations.
Here are the javadocs for the classes used above:
Retention annotation
RetentionPolicy enum
Target annotation
Field class
isAnnotationPresent() method
getDeclaredFields() method
I'm trying to understand your car example, but I'm not sure I follow what you want.
If you had a list of objects (Jaguar, Porche, Ferrari, Kia) that extend Car and are marked with various car-related annotations, you could create an object that filters the list based on annotations.
The code might look like this:
#WorldsFinestMotorCar
class Jaguar extends Car {
// blah blah
}
#BoringCar
class Porche extends Car {
// blah blah
}
#BoringCar
class Ferrari extends Car {
// blah blah
}
#IncredibleCar
class Kia extends Car {
// blah blah
}
You could implement an AnnotationFilter class that removes cars from the list that do not have a certain annotation.
It might look something like this:
List<Car> carList = getListOfRandomCars();
AnnotationFilter<Car> annoFilter = new AnnotationFilter<Car>(BoringCar.class);
List<Car> boringCars = annoFilter.filter(carList);
Is that what you want to do?
If so, it can definitely be done.
The implementation for AnnotationFilter might look something like this:
public class AnnotationFilter<T> {
private Class filterAnno;
public AnnotationFilter(Class a) {
filterAnno = a;
}
public List<T> filter(List<T> inputList) {
if (inputList == null || inputList.isEmpty()) {
return inputList;
}
List<T> filteredList = new ArrayList<T>();
for (T someT : inputList) {
if (someT.getClass().isAnnotationPresent(filterAnno)) {
filteredList.add(someT);
}
}
return filteredList;
}
}
If that's not what you're after, a specific example would be helpful.
Java haven't got anything built in as such, which is why Reflections came about. Nothing built in that's as particular as what you're saying..
User-defined Annotations: we shall see how to annotate objects that we may come across in day-to-day life. Imagine that we want to persistent object information to a file. An Annotation called Persistable can be used for this purpose. An important thing is that we want to mention the file in which the information will get stored. We can have a property called fileName within the declaration of Annotation itself. The definition of the Persistable Annotation is given below,
Persistable.java
#Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
public #interface Persistable
{
String fileName();
}
Annotations are just a way of tagging elements of a class; how these annotations are interpreted is up to the code that defines these annotations.
Is there some built-in way of handling annotations?
Annotations are used in so many different ways that it would be difficult to come up with a few "built-in ways" of handling them. There are source-level annotations (such as #Override and #Deprecated) that do not affect the behaviour of the code at all. Then there are runtime annotations that are usually very specific to a certain library, for eg. JAXB's binding annotations only make sense within a JAXBContext and Spring's autowiring annotations only make sense within an ApplicationContext. How would Java know what to do with these annotations simply by looking at a class which uses them?

Canonicalizing Java bean property names

I have a bunch of third-party Java classes that use different property names for what are essentially the same property:
public class Foo {
public String getReferenceID();
public void setReferenceID(String id);
public String getFilename();
public void setFilename(String fileName);
}
public class Bar {
public String getRefID();
public void setRefID(String id);
public String getFileName();
public void setFileName(String fileName);
}
I'd like to be able to address these in a canonicalized form, so that I can treat them polymorphically, and so that I can do stuff with Apache BeanUtils like:
PropertyUtils.copyProperties(object1,object2);
Clearly it would be trivial to write an Adapter for each class ...
public class CanonicalizedBar implements CanonicalizedBazBean {
public String getReferenceID() {
return this.delegate.getRefID();
}
// etc.
}
But I wonder is there something out there more generalized and dynamic? Something that would take a one-to-many map of property name equivalences, and a delegate class, and produce the Adapter?
I've never used it, but I think you're looking for Dozer:
Dozer is a Java Bean to Java Bean mapper that recursively copies data
from one object to another. Typically, these Java Beans will be of
different complex types.
Dozer supports simple property mapping, complex type mapping,
bi-directional mapping, implicit-explicit mapping, as well as
recursive mapping. This includes mapping collection attributes that
also need mapping at the element level.
Dozer not only supports mapping between attribute names, but also
automatically converting between types. Most conversion scenarios are
supported out of the box, but Dozer also allows you to specify custom
conversions via XML.
First Option is Dozer.
Second option is Smooks Framework
with a tweak. It will be beneficial to use Smook's Graphical mapper.
Another option would be XStream with custom Mapper.
maybe something like that:
public class CanonicalizedBar implements CanonicalizedBazBean {
public String getReferenceID() {
Method m = this.delegate.getClass().getDeclaredMethod("getReferenceID");
if(m == null)
m = this.delegate.getClass().getDeclaredMethod("getRefID");
...
return m.invoke();
}
// etc.
}
Although, I personally have never used it. I noticed that a project called orika is noted as having the best performance and the ability to automatically understand many such mappings.
At any rate it also supports custom mappings and uses generated code to implicitly define the adapters.
You can also define a custom mapper, that is if you know how to canonize the member names you can use that knowledge to build a mapping that is true for all your objects. for instance:
DefaultFieldMapper myDefaultMapper = new DefaultFieldMapper() {
public String suggestMapping(String propertyName, Type<?> fromPropertyType) {
// split word according to camel case (apache commons lang)
String[] words= StringUtils.splitByCharacterTypeCamelCase(propertyName);
if(words[0].length() > 6) {
// trim first camel-cased word of propery name to 3 letters
words[0]= words[0].substring(0,2);
return StringUtils.join(words);
} else {
// remains unchanged
return propertyName;
}
}
}
mapperFactory.registerDefaultFieldMapper(myDefaultMapper );
I haven't done much with it but you may be able to use Aspect Oriented Programming to do this.
What you should be able to do I think is add a method to each of the classes that internally calls the real method. See this article about half way down it talks about mixins.
AspectJ is probably the most popular implementation.

Can you use Java Reflection api in GWT client

IS it possible to use the java reflection api in GWT client side? I want to use reflections to find the value of a property on a Javabean. Is this possible?
You can use the GWT Generators functionality that allows you to generate code during the GWT compile phase.
Your bean, that you want to introspect, can extend a class that has a method defined as
public Object getProperty(String propertyName){}
Let's call this class IntrospectionBean.
Let's say that you then have your bean defined as:
public class MyBean extends IntrospectionBean {
private String prop1;
private String prop2;
}
The GWT generator will have access to all fields of MyBean and it can generate the getProperty(String propertyName) method during GWT compile time, after iterating through all fields of MyBean.
The generated class might look like this:
public class MyBean extends IntrospectionBean {
private String prop1;
private String prop2;
public Object getProperty(String propertyName) {
if ("propr1".equals(propertyName)) {
return prop1;
}
if ("propr2".equals(propertyName)) {
return prop2;
}
return null;
}
}
You could simply then use myBean.getProperty("prop1") in order to retrieve a property based on it's name at runtime.
Here you can find an example of how to implement a gwt generator
I've been there and the solution indeed is to use Deferred Binding and Generators. You can see a use of Generators to overcome the lack of Reflection in GWT client here:
http://jpereira.eu/2011/01/30/wheres-my-java-reflection/
Hope it helps.
Since GWT code is translated to Javascript direct usage of reflection API is not supported.
There is a small project GWT-Reflection, that allows to use reflection in GWT.
I have made my gwt-reflection library public.
https://github.com/WeTheInternet/xapi/tree/master/gwt/gwt-reflect
https://github.com/WeTheInternet/gwt-sandbox/tree/xapi-gwt/user/src/com/google/gwt/reflect
Due to classpath issues with trying to make Gwt pick my version of Class.java over its own, I finally just forked Gwt, added java 8 and reflection support, and now maintain net.wetheinter:gwt-*:2.7.0 which has this support baked in (I will release a 2.8 some time after Gwt 2.8 goes live)
It supports three levels of reflection:
Monolithic:
// Embeds all data needed to perform reflection into hidden fields of class
GwtReflect.magicClass(SomeClass.class);
SomeClass.getField(fieldName).set(null, 1);
Lightweight:
// Allows direct reflection, provided ALL parameters are literals, or traced to literals
SomeClass.class.getField("FIELD_NAME").set(null, 1);
Flyweight:
// Skips creating a Field object entirely, and just invokes the accessor you want
// All params must be literals here as well
GwtReflect.set(SomeClass.class, "FIELD_NAME", null, 1);
These examples also work for Methods and Constructors. There's basic support for annotations, and more to come in the future.
GWT not support reflection fully, you can see bellow link :
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsCompatibility.html
You should note the border between java and javascript. In GWT, all code compiles to javascript, so you have to check if JavaScript is a well-defined reflection.
If you just want to use reflection to grab a private field, consider using jsni (javascript native interface) instead; it has no notion of private or public, so you can just grab anything you want like so:
package com.foo;
class SomeClass {
private String someField;
private static int someInt;
}
//accessors:
native String ripField(SomeClass from)
/*-{
return from.#com.foo.SomeClass::someField;
}-*/;
native int ripInt()
/*-{
return #com.foo.SomeClass::someInt;
}-*/;
Also, I am in the middle of finishing up emulation for java.lang.Class newInstance / reflection.
I'll post back here with a link in about two days if you'd like to play with it.
It requires that you pass a class through a method which I route to a custom generator
(like GWT.create, except it returns a generated java.lang.Class with field and method accessors that just point to jsni methods / fields. :)

How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java?

I've been converting some code from java to scala lately trying to teach myself the language.
Suppose we have this scala class:
class Person() {
var name:String = "joebob"
}
Now I want to access it from java so I can't use dot-notation like I would if I was in scala.
So I can get my var's contents by issuing:
person = Person.new();
System.out.println(person.name());
and set it via:
person = Person.new();
person.name_$eq("sallysue");
System.out.println(person.name());
This holds true cause our Person Class looks like this in javap:
Compiled from "Person.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
public Person();
public void name_$eq(java.lang.String);
public java.lang.String name();
}
Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname");
Note: I'd much rather have to put up with this rather than fill my classes with more setter methods.
So what would you do in this situation?
You can use Scala's bean property annotation:
class Person() {
#scala.reflect.BeanProperty
var name:String = "joebob"
}
That will generate getName and setName for you (useful if you need to interact with Java libraries that expect javabeans)

Categories

Resources