I'm using CachedRowSet. But when I call the insertRow() method, there is a SQLException failed to insert row.
Here is my code:
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/javapos";
static final String USERNAME = "root";
static final String PASSWORD = "sbc";
public static void main (String [] agr) throws SQLException
{
CachedRowSetImpl rs = new CachedRowSetImpl();
rs.setUrl(DATABASE_URL);
rs.setUsername(USERNAME);
rs.setPassword(PASSWORD);
rs.setCommand("select * from uom order by itemid");
rs.execute();
while(rs.next()){
System.out.println(rs.getString("itemid") + " - " + rs.getString("uom"));
}
rs.moveToInsertRow();
rs.updateString(2,"Sample code");
rs.insertRow();
rs.moveToCurrentRow();
rs.acceptChanges();
}
When you call insertRow(), the Reference Implementation of CachedRowSet performs a check if all required columns have been populated and otherwise it throws an exception (source from Grepcode CachedRowSet.insertRow(), line numbers don't exactly match):
if (onInsertRow == false ||
insertRow.isCompleteRow(RowSetMD) == false) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.failedins").toString());
}
The check is performed in InsertRow.isCompleteRow(RowSetMetaData):
public boolean isCompleteRow(RowSetMetaData RowSetMD) throws SQLException {
for (int i = 0; i < cols; i++) {
if (colsInserted.get(i) == false &&
RowSetMD.isNullable(i + 1) == ResultSetMetaData.columnNoNulls) {
return false;
}
}
return true;
}
In other words, when inserting a row you must provide a value for all columns that are not nullable (this includes the primary key). There seem to be two ways to work around this:
Setting a (random) value. This does require that your primary key is always generated (even if a value is provided).
Explicitly setting the column to null using updateNull. Using setNull doesn't work: it provides the same error, and using setObject(idx, null) results in a NullPointerException
When using your code with these changes I get an SQLException when calling acceptChanges as the implementation doesn't disable autoCommit (it seems to have been commented out), but it does explicitly call commit (which is invalid when in autoCommit). This doesn't seem to be easy to solve, except maybe explicitly providing a connection on execute, or creating your own implementation.
I think these kind of issues actually demonstrate how little the RowSet implementations are actually used (otherwise they would already have been flushed out long ago).
Note however that if this were the actual code you needed and don't need the disconnected characteristics of the CachedRowSet, then you could simply use an updatable result set.
Example:
beginAddRow(crs);
crs.updateString("TABLE_TYPE", "TABLE");
continueAddRow();
crs.updateString("TABLE_TYPE", "INDEX");
endAddRow();
static public CachedRowSet beginAddRow(CachedRowSet crs) throws SQLException {
crs.moveToInsertRow(); // onInsertRow = true
return crs;
}
static public CachedRowSet continueAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow();
crs.moveToInsertRow();
return crs;
}
static public CachedRowSet endAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow(); // onInsertRow = false;
crs.beforeFirst();
return crs;
}
Related
I am checking that submitted data is not null but on simply submitting(no data) it is still inserting in the database and also i have made my columns not null but data is still getting inserted.I don't know why?
IN my Servlet
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=checknull.value(department);
boolean checkc=checknull.value(company);
boolean checkp=checknull.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("inserted.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsered.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
This is the java class which is checking
public class checknull {
static boolean ch;
public static boolean value(String check)
{
ch = check != null;
return ch;
}
Modify your checknull class to:
public class checknull
{
// static boolean ch; (You don't need this static variable)
public static boolean value(String check)
{
return check != null && check.length() > 0;
}
}
Also, it's a convention in Java to have class names in UpperCase.
Example:
public class CheckNull
EDIT:
As suggested by Erwin Bolwidt, it's very likely that the database being used here is Oracle, since Oracle equates empty strings and nulls.
Therefore, this answer is only applicable to databases that treat empty strings as nulls (e.g. Oracle).
See: null-vs-empty-string-in-oracle
First, I'll give the codes I'm dealing with.
Action code for the "Save" Button.
private void saveBtActionPerformed(java.awt.event.ActionEvent evt) {
try {
Production production=new Production(batchNoValueLabel.getText(), productIDCombo.getSelectedItem(), rawMaterialUsedCombo.getSelectedItem(), dateValueLabel.getText(), rawMaterialBatchCombo.getSelectedItem(), weightInitialSpinner.getValue(), beforeWeightSpinner.getValue(), afterWeightSpinner.getValue(), finalWeightSpinner.getValue(), packingWeightSpinner.getValue(), noOfUnitSpinner.getValue(), wastageSpinner.getValue());
int res=ProductionController.addBatch(production);
if(res==1){
JOptionPane.showMessageDialog(this, "New Batch Added!");
String nextid = IDGeneration.getNextid("B", "production", "productionBatchID");
batchNoValueLabel.setText(nextid);
productIDCombo.removeAllItems();
ArrayList<String> getProductsDetails = ProductsController.getProductID();
for (String detail : getProductsDetails) {
productIDCombo.addItem(detail);
}
}else{
JOptionPane.showMessageDialog(this, "New Product Adding Failed!");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(ProductsForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
Then, the Model Class. (Getters and Setters are there, not pasted here)
public Production(String productionBatchID, Object finishedMaterialID, Object rawMaterialID, String productionDate, Object rawMatBatchID, Object initialWeight, Object beforeWeight, Object afterWeight, Object finalWeight, Object packingWeight, Object noOfUnits, Object wastage) {
this.productionBatchID = productionBatchID;
this.finishedMaterialID = (String) finishedMaterialID;
this.rawMaterialID = (String) rawMaterialID;
this.productionDate = productionDate;
this.rawMatBatchID = (String) rawMatBatchID;
this.initialWeight = (int) initialWeight;
this.beforeWeight = (int) beforeWeight;
this.afterWeight = (int) afterWeight;
this.finalWeight = (int) finalWeight;
this.packingWeight = (int) packingWeight;
this.noOfUnits = (int) noOfUnits;
this.wastage = (int) wastage;
}
And, finally the controller class.
public class ProductionController {
public static int addBatch(Production production) throws ClassNotFoundException, SQLException {
Connection conn=DBConnection.getConnection();
Statement stm=conn.createStatement();
String sql="insert into production (productionBatchID, finishedMaterialID, rawMaterialID, productionDate, rawMatBatchID, initialWeight, beforeWeight, finalWeight, packingWeight, noOfUnits, wastage) values ('"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+production.getBeforeWeight()+"','"+production.getAfterWeight()+"','"+production.getFinalWeight()+"','"+production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+production.getWastage()+"');";
int rowCount=stm.executeUpdate(sql);
return rowCount;
}
}
And still, when I enter data in the GUI and try to send the data to the database, it gives out "java.sql.SQLException: Column count doesn't match value count at row 1" error. How to solve this? Oh, and here's the MySQL Table:
create table production(productionBatchID VARCHAR(4) NOT NULL,finishedMaterialID VARCHAR(4) NOT NULL,rawMaterialID VARCHAR(4) NOT NULL,productionDate VARCHAR(15),rawMatBatchID VARCHAR(4),initialWeight INT(5),beforeWeight INT(5),afterWeight INT(5),finalWeight INT(5),packingWeight INT(5),noOfUnits INT(5),wastage INT(5),CONSTRAINT PRIMARY KEY (productionBatchID))ENGINE=INNODB;
How to solve this?
Your VALUES clause has
'"+production.getAfterWeight()+"','"+production.getFinalWeight()+
But you only have finalWeight in the column list.
The error tells you this
insert into production (
productionBatchID, finishedMaterialID,
rawMaterialID, productionDate,
rawMatBatchID, initialWeight,
beforeWeight, finalWeight,
packingWeight, noOfUnits,
wastage)
values (
'"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+
production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+
production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+
production.getBeforeWeight()+"','"+
production.getAfterWeight()+"','"+
production.getFinalWeight()+"','"+ there are 3 here
production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+
production.getWastage()+"');";
Also, parameterise your queries to mitigate SQL Injection risks please
There is mismatch in number of columns you are using in INSERT query, 'beforeWeight' is the column, whose values is missing, below is the corrected query:
String sql="insert into production (productionBatchID, finishedMaterialID, rawMaterialID, productionDate, rawMatBatchID, initialWeight, **beforeWeight**, finalWeight, packingWeight, noOfUnits, wastage) values ('"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+production.getBeforeWeight()+"','"+production.getAfterWeight()+"','"+production.getBeforeWeight()+"','"+production.getFinalWeight()+"','"+production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+production.getWastage()+"');";
I use a Row Set to pass query results in my selenium framework. Occasionally the data access object throws the following
java.sql.SQLException: No suitable driver found for jdbc:jtds:sqlserver://MYDatabasename:1433/DB
It uses this same driver and rowset to access and only fails occasionally. Any help would be appreciated.
RowSet:
public static RowSet GetRowSet(String SqlQuery, String[] Parameters, String DB){
CachedRowSet rs;
String ROWSET_IMPL_CLASS = "com.sun.rowset.CachedRowSetImpl";
rs = null;
try {
Class<?> c = Class.forName(ROWSET_IMPL_CLASS);
rs = (CachedRowSet) c.newInstance();
rs.setUrl(Configuration.DBConnString + DB);
rs.setUsername(Configuration.DBUser );
rs.setPassword(Configuration.DBPwd );
rs.setReadOnly(true);
rs.setCommand(SqlQuery);
for (int p=0;
p<Parameters.length;
p++)
{
rs.setString(p+1, Parameters[p]);
}
rs.execute();
Example of code:
public void examplevoid(String string, String string2)
throws Exception {
RowSet RoS = null;
RoS = Example.GetExample(string, string2);
while (RoS.next()) {
String Example = RoS.getString("Example");
selenium.click(Example)
selenium.waitForPageToLoad(setup.timeoutsetting);
}
RoS.close();
Which uses and in turn calls the rowset:
public static RowSet GetExample(String string, String string2) throws
String[] Parameters = {string, string2};
RowSet ExampleRowSet= null;
ExampleRowSet = DataAccess.GetRowSet("Some SQL HERE", Parameters, Configuration.DB);
return Example;
That seems impossible. Either the driver class is loaded, or it isn't. Once loaded, successive calls to DriverManager.getConnection() with the same JDBC URL should never give that error. What else is going on?
Edit: The only questionable thing I see is that all of your Configuration.* properties appear to be fields in a class somewhere. If some of those properties are changing values between tests, maybe your JDBC driver is causing that exception to be thrown because of a bad property value, like the Configuration.DB or Configuration.DBConnString. If it's fairly repeatable, try changing
rs.setUrl(Configuration.DBConnString + DB);
to
String url = Configuration.DBConnString + DB;
log.debug("Using JDBC URL: " + url);
rs.setUrl(url);
When the exception happens, see if the string looks different.
OK, I have a JSP running the following script section.
<% irCollection mgrq = new irCollection();
mgrq.setMgrid("Chris Novish");
mgrq.populateCollection();
int pagenum;
if (request.getParameter("p") != null) {
String pagedatum=request.getParameter("p");
pagenum = Integer.parseInt(pagedatum);
} else { pagenum = 0; }
for (int i=0;i<10;i++) {
int rownum = pagenum * 10 + i;
InquireRecord currec = mgrq.getCurRecords(rownum);
out.println(currec.getID()); %>
irCollection has an ArrayList property that stores a several InquireRecord objects. It gets this data from a database using the mgrid as (set in line 2 there) as the matching term.
But I'm getting an IndexOutOfBounds exception on what appears here as line 11.
I've done some tests, and I'm pretty sure that it's because populateCollection() isn't getting things done. I have a getSize method that gives me a size of 0.
I made a test class in Eclipse to make sure all my methods were working:
package com.serco.inquire;
public class test {
public static void main (String[] args) {
String mgr = "Chris Novish";
irCollection bob = new irCollection();
bob.setMgrid(mgr);
bob.populateCollection();
InquireRecord fred = bob.getCurRecords(1);
System.out.println(fred.getID());
}
}
That test class produces exactly what I'd expect.
Other than the names of some of the local variables, I can't see what I'm doign different in the JSP.
So... tell me, what noobish mistake did I make?
for the sake of being thorough, here's the populateCollection() method:
public void populateCollection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "inquire.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute ("SELECT * FROM inquiries WHERE manager = '" + mgrid + "'");
ResultSet rs = s.getResultSet();
int cur;
if (rs != null) {
while (rs.next()) {
cur = rs.getRow();
cur -- ;
int curID = rs.getInt("ID");
this.newIR.setID(curID);
String cursub = rs.getString("submitter");
this.newIR.setSubmitter(cursub);
this.iRecords.add(cur, this.newIR);
}
this.size = iRecords.size();
this.pages = this.size / 10;
int remain = this.size % 10;
if (remain > 0) { this.pages++; }
} else { System.out.println("no records."); }
}
catch (Throwable e) {
System.out.println(e);
}
}
Your IndexOutOfBounds exception is probably being caused by the value of rownum being passed to mgrq.getCurRecords().
Your test code proves nothing because there you're calling getCurRecords() with a constant which is probably always valid for your system and will never cause the exception.
My suggestion is to step through the code in your JSP with a debugger, or even simply to print out the value of your variables (especially pagedatum, pagenum and rownum) in your JSP code.
Is your JSP Snippet correct? It looks like you started the braces for the
for (int i=0;i<10;i++) {
but I dont see a end braces for that at all. Can you check if that is the case and if so, fix the code appropriately?
I have tried to find information about this but have come up empty handed:
I gather it is possible to create a class dynamically in Java using reflection or proxies but I can't find out how. I'm implementing a simple database framework where I create the SQL queries using reflection. The method gets the object with the database fields as a parameter and creates the query based on that. But it would be very useful if I could also create the object itself dynamically so I wouldn't have the need to have a simple data wrapper object for each table.
The dynamic classes would only need simple fields (String, Integer, Double), e.g.
public class Data {
public Integer id;
public String name;
}
Is this possible and how would I do this?
EDIT: This is how I would use this:
/** Creates an SQL query for updating a row's values in the database.
*
* #param entity Table name.
* #param toUpdate Fields and values to update. All of the fields will be
* updated, so each field must have a meaningful value!
* #param idFields Fields used to identify the row(s).
* #param ids Id values for id fields. Values must be in the same order as
* the fields.
* #return
*/
#Override
public String updateItem(String entity, Object toUpdate, String[] idFields,
String[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ");
sb.append(entity);
sb.append("SET ");
for (Field f: toUpdate.getClass().getDeclaredFields()) {
String fieldName = f.getName();
String value = new String();
sb.append(fieldName);
sb.append("=");
sb.append(formatValue(f));
sb.append(",");
}
/* Remove last comma */
sb.deleteCharAt(sb.toString().length()-1);
/* Add where clause */
sb.append(createWhereClause(idFields, ids));
return sb.toString();
}
/** Formats a value for an sql query.
*
* This function assumes that the field type is equivalent to the field
* in the database. In practice this means that this field support two
* types of fields: string (varchar) and numeric.
*
* A string type field will be escaped with single parenthesis (') because
* SQL databases expect that. Numbers are returned as-is.
*
* If the field is null, a string containing "NULL" is returned instead.
*
* #param f The field where the value is.
* #return Formatted value.
*/
String formatValue(Field f) {
String retval = null;
String type = f.getClass().getName();
if (type.equals("String")) {
try {
String value = (String)f.get(f);
if (value != null) {
retval = "'" + value + "'";
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else if (type.equals("Integer")) {
try {
Integer value = (Integer)f.get(f);
if (value != null) {
retval = String.valueOf(value);
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else {
try {
String value = (String) f.get(f);
if (value != null) {
retval = value;
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
}
return retval;
}
There are many different ways to achieve this (e.g proxies, ASM), but the simplest approach, one that you can start with when prototyping is:
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";
public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}
public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();
new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
// public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==-1);
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
It is possible to generate classes (via cglib, asm, javassist, bcel), but you shouldn't do it that way. Why?
the code that's using the library should expect type Object and get all the fields using reflection - not a good idea
java is statically typed language, and you want to introduce dynamic typing - it's not the place.
If you simply want the data in an undefined format, then you can return it in an array, like Object[], or Map<String, Object> if you want them named, and get it from there - it will save you much trouble with unneeded class generation for the only purpose of containing some data that will be obtained by reflection.
What you can do instead is have predefined classes that will hold the data, and pass them as arguments to querying methods. For example:
public <T> T executeQuery(Class<T> expectedResultClass,
String someArg, Object.. otherArgs) {..}
Thus you can use reflection on the passed expectedResultClass to create a new object of that type and populate it with the result of the query.
That said, I think you could use something existing, like an ORM framework (Hibernate, EclipseLink), spring's JdbcTemplate, etc.
This is possible, but (I believe) you need something like ASM or BCEL.
Alternately, you could use something with more power (like Groovy).
It will take a couple of minutes to create a data model class for each table, which you can easily map to the database with an ORM like Hibernate or by writing your own JDBC DAOs. It is far easier than delving deeply into reflection.
You could create a utility that interrogates the database structure for a table, and creates the data model class and DAO for you. Alternatively you could create the model in Java and create a utility to create the database schema and DAO from that (using reflection and Java 5 Annotations to assist). Don't forget that javaFieldNames are different from database_column_names typically.
Recently I needed to create about 200 simple classes from medatata (objects filled with static data) and I did it through the open source burningwave library, with the following scenario:
The classes needed to have a certain prefix in the name, for example "Registro "*.java;
The classes needed to extend from a superclass Registro.java
The classes needed to contain JPA annotations like #Entity, #Column (in attributes), Lombok annotations and custom annotations.
Here is the link to the repository with the complete project: https://github.com/leandrosoares6/criacao-classes-entidade-efd
Here is the code snippet responsible for creating the classes:
public class RegistrosClassFactory {
private static final String PACOTE = "com.example.demo.model.registros";
private static final String SCHEMA = "MY_SCHEMA";
private static final String PREFIXO = "Registro";
static void criaRegistros() {
List<RegistroTest> registros = RegistroMetadataFactory.criaMetadados();
criaClasses(registros);
}
private static void criaClasses(List<RegistroTest> registros) {
for (RegistroTest registroTest : registros) {
UnitSourceGenerator gerador = UnitSourceGenerator.create(PACOTE);
ClassSourceGenerator registro = ClassSourceGenerator
.create(TypeDeclarationSourceGenerator.create(PREFIXO + registroTest.getNome()))
.addModifier(Modifier.PUBLIC)
.addAnnotation(AnnotationSourceGenerator.create(Getter.class))
.addAnnotation(AnnotationSourceGenerator.create(Setter.class))
.addAnnotation(AnnotationSourceGenerator.create(NoArgsConstructor.class))
.addAnnotation(AnnotationSourceGenerator.create(ToString.class))
.addAnnotation(AnnotationSourceGenerator.create(Entity.class))
.addAnnotation(AnnotationSourceGenerator.create(Table.class)
.addParameter("name",
VariableSourceGenerator.create(String.format("\"%s\"",
registroTest.getNomeTabelaBd())))
.addParameter("schema", VariableSourceGenerator
.create(String.format("\"%s\"", SCHEMA))));
criaColunas(registroTest.getCampos(), registro);
registro.addConstructor(FunctionSourceGenerator.create().addModifier(Modifier.PUBLIC)
.addParameter(VariableSourceGenerator.create(String.class, "linha"))
.addBodyCodeLine("super(linha);")).expands(Registro.class);
gerador.addClass(registro);
// System.out.println("\nRegistro gerado:\n" + gerador.make());
String caminhoPastaRegistros = System.getProperty("user.dir") + "/src/main/java/";
gerador.storeToClassPath(caminhoPastaRegistros);
}
}
private static void criaColunas(List<Campo> campos, ClassSourceGenerator registro) {
for (Campo campo : campos) {
VariableSourceGenerator field = VariableSourceGenerator
.create(TypeDeclarationSourceGenerator.create(String.class),
campo.getNomeAtributo())
.addModifier(Modifier.PRIVATE)
.addAnnotation(AnnotationSourceGenerator.create(Column.class)
.addParameter("name", VariableSourceGenerator
.create(String.format("\"%s\"", campo.getNome())))
)
.addAnnotation(AnnotationSourceGenerator.create(Indice.class).addParameter(
"valor",
VariableSourceGenerator.create(String.valueOf(campo.getSequencial()))));
if (campo.getNome().equals("ID")) {
field.addAnnotation(AnnotationSourceGenerator.create(Id.class));
}
if (campo.getEId()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoId.class));
}
if (campo.getEData()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoData.class));
}
if (campo.getEDataPart()) {
field.addAnnotation(AnnotationSourceGenerator.create(CampoTipoDataPart.class));
}
registro.addField(field);
}
}
}
I'm aware of the performance drawback of reflection but for my little project I needed this and I created a project lib which converts JSON to Java and then finally .class in JVM context.
Anyone need such thing can have a look into my open source solution, which requires JDK to compile the code.
https://medium.com/#davutgrbz/the-need-history-c91c9d38ec9?sk=f076487e78a1ff5a66ef8eb1aa88f930