I have some classes in my project and when I want to instantiate object from them using myClass.newInstance() to build SQL queries, it just creates the object with one field and I can't retrieve all class fields to complete my query. When I get size of my object it returns '1' instead of '3'.
Any idea what should I do?
Here-under you can find one class and my query builder.
#JupiterEntity
#TableName(name="tbl_person")
public class Person {
#PrimaryKey
#DbColumn(name = "clmn_id")
private int id;
#DbColumn(name="clmn_name", length = 1024)
private String name;
#DbColumn(name="clmn_family", length = 1024)
private String family;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
And here is when I want to instantiat an object from my class:
public MySQLEntityManager() {
StringBuilder stringBuilder = new StringBuilder();
if(ServiceLocator.getConfiguration().createDDL()) {
for(Class entityClass : ServiceLocator.getConfiguration().getEntities()) {
Object obj = new Object();
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
stringBuilder.append("DROP TABLE ")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
System.out.println(stringBuilder.toString());
stringBuilder.setLength(0);
stringBuilder.append("CREATE TABLE")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
Map<Field, Object> fields = ReflectionHelper.getValuesOfFields(obj);
for(Field field : fields.keySet()) {
System.out.println(field.getName() + " -> " + fields.get(field));
}
String delimiter = "";
for (Field field : fields.keySet()) {
String columnName = field.getName();
if (field.isAnnotationPresent(DbColumn.class)) {
DbColumn dbColumn = field.getAnnotation(DbColumn.class);
columnName = dbColumn.name();
}
stringBuilder.append(delimiter).append(columnName);
delimiter = ", ";
}
System.out.println("*****" + stringBuilder.toString());
delimiter = "";
System.out.println(stringBuilder.toString());
}
}
}
So the problem is that ReflectionHelper.getValuesOfFields(obj) isn't returning what you want. You can debug that, or use obj.getClass().getDeclaredFields() instead of some NIH junk.
Related
I have json file from which I parse json objects to java objects using Gson library. The next step is to create main class in which with the help of Apache POI prepared docx file is read, some changes were made in the text and new document with changes is created. The problem I faced is that the text which should be changed need to be variable(from json file). I mean that "name" and "testName" both should be variables or methods, so I can call them from text.contains. Can you show my mistake and the right way to do the task. Thanks in advance.
Here is my code `
public class main {
public static void gson() {
Gson gson = new Gson();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("jsonn.json"));
Result result = gson.fromJson(br, Result.class);
if (result != null) {
result.getName();
result.getLastname();
System.out.println(result.getName());
System.out.println(result.getLastname());
for (Phone p : result.getPhones()) {
p.getType();
p.getNum();
System.out.println(p.getType() + ": " + p.getNum());
// System.out.println(p.getType()+" : "+p.getNum());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
public class Result {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lastname")
#Expose
private String lastname;
#SerializedName("phones")
#Expose
private List<Phone> phones = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}}
public class Phone {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lastName")
#Expose
private String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#SerializedName("num")
#Expose
private String num;
#SerializedName("type")
#Expose
private String type;
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}}
public class Read {
public static void main(String[] args) throws InvalidFormatException,
IOException {
main.gson();
XWPFDocument doc = new XWPFDocument(OPCPackage.open("Шаблон.docx"));
Result res = new Result();
String replaceName = res.getName();
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("name")) {
text = text.replace("name", "Alex");
r.setText(text, 0);
}
}
}
}
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.contains("name")) {
text = text.replace("name", "Alex");
r.setText(text, 0);
}
}
}
}
}
}
doc.write(new FileOutputStream("Пример.docx"));
}}
`
Here is json file:
{
"name":"testName",
"lastname":"testLastName",
"phones":[
{
"num":"9000000",
"type":"mobile"
},
{
"num":"1000000",
"type":"home"
} ]}
So I have a class that creates a company object from my database table
public class Company {
private int id;
private String name;
private double marketValue;
private double lastValue;
private double currentValue;
private String ticker;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMarketValue() {
return marketValue;
}
public void setMarketValue(double marketValue) {
this.marketValue = marketValue;
}
public double getLastValue() {
return lastValue;
}
public void setLastValue(double lastValue) {
this.lastValue = lastValue;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public double getCurrentValue() {
return currentValue;
}
public void setCurrentValue(double currentValue) {
this.currentValue = currentValue;
}
public String toString() {
return ("Name of Company: " + this.name + ", Last stock price: " + this.lastValue + ", Company Cap: " + this.marketValue + ", ID: " + this.id);
}
public static ArrayList<Company> getCompanies() throws Exception {
ArrayList<Company> companyList = new ArrayList<Company>();
try {
Connection conn = null;
conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT companies.companies_id, companies.Companies, companies.ticker, companies.marketcap, stockvalue.lastprice FROM stocks.companies, stocks.stockvalue WHERE companies.companies_id = stockvalue.stockvalue_id");
while (result.next()) {
Company company = new Company();
company.setId(result.getInt("companies_id"));
company.setName(result.getString("Companies"));
company.setMarketValue(result.getDouble("marketcap"));
company.setLastValue(result.getDouble("lastprice"));
company.setTicker(result.getString("ticker"));
companyList.add(company);
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
return companyList;
}
}
and then I display that object with a jTable
public class Operations {
private static final String[] COLUMNS = {"Company", "Stock Price"};
public static DefaultTableModel createTableModel() throws Exception {
DefaultTableModel tableModel = new DefaultTableModel(COLUMNS, 0);
ArrayList<Company> companyList = Company.getCompanies();
for (int i = 0; i < companyList.size(); i++) {
Object[] row = {companyList.get(i).getName(), companyList.get(i).getLastValue()};
tableModel.addRow(row);
}
return tableModel;
}
}
But now, I want to take this one step further and keep a record of stock values by date in my table, so for instance now I have this:
https://postimg.org/image/r0v3up2fx/
and tomorrow my program will add an additional column labeled 12_13_16 and the next day 12_14_16, etc.
In these two classes, how would I go about adding those columns I create daily to the object, and then making the jTable display that additional column every day?
I can't figure out a solution besides manually adding a new set/get method for every new column every time my table updates.
Maybe you can use ResultSet.getMetaData() to find your desired table schema.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
Im quite new to Rhino and trying to convert a javascript object to a java object but unable to do so. It doesnt seem to evaluate properly.
The javascript that I have is,
var myObject = new Object();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And I have the following java class that I want to evaluate this to,
public class Person extends ScriptableObject {
private int id;
private String string1;
private String string2;
public Person() {}
public void jsConstructor() {
this.string1 = "";
this.string2 = "";
this.id = 0;
}
public int getID()
{
return this.id;
}
public void jsSet_id(int value)
{
this.id = value;
}
public int jsGet_id()
{
return this.id;
}
public String jsGet_string1()
{
return this.string1;
}
public void jsSet_string1(String value)
{
this.string1 = value;
}
public String jsGet_string2() {
return this.string2;
}
public void jsSet_string2(String value)
{
this.string2 = value;
}
#Override
public String toString() {
return id + " " + string1 + " " + string2;
}
#Override
public String getClassName() {
return "Person";
}
And the skeleton of my parser is,
public class MyParser {
public String PrintObj(ScriptableObject obj) {
// Need to convert to Person object here
// Obviously casting doesnt work here
return null;
}
}
Thanks
OK figured it out !
First of all i needed to define the class in javascript as. It was complaining at first it couldn't find the class without the namespace "com". Had to add that...
defineClass("com.Person")
var myObject = new Person();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And then in the parser I added the following,
public String PrintObj(ScriptableObject obj) {
try {
Person pObj = (Person)Context.jsToJava(obj, Person.class);
System.out.println("Printing person: " + pObj);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am trying replace the arrays I have with arraylists so I don't have to worry about managing the arrays and can clean up my code. I have only just taught myself arraylists so I am having some issues. Mainly in these classes where all my "sets" and "gets" are. I don't think I have the right syntax because I am getting an ArrayList/String conflict error. Basically trying to get:
public static ArrayList<Resource> importResourcesFromXML(String documentLocation)
to import an arraylist of resources from an XML document. I also wanted to convert my arrays in Resources and my T_Resources into arraylists as well. This is the code I have so far, I believe I have Resources implemented correctly but could use help with the other two getting the XML resources to display properly.
EDIT: I want to if at all possible eliminate the array entirely and replace it with an arraylist. I want to try and avoid converting an array to an arraylist.
import java.util.ArrayList;
public class Resources {
//private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
ArrayList<Subject> subject = new ArrayList<Subject>();
//private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
//subjects = new Subject[MAX_SUBJECTS];
//subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subject.add(newSubject);
}
public ArrayList<Subject> getSubjects() {
//Subject[] result = new Subject[subjectCount];
//System.arraycopy(subjects, 0, result, 0, subjectCount);
return subject;
}
}
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static ArrayList<Resource> importResourcesFromXML(String documentLocation) {
ArrayList<Resource> resource = new ArrayList<Resource>();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
import java.util.ArrayList;
public class T_Resources {
public static void main(String[] args) {
ArrayList<Resource> resource = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resource);
}
private static void displayResources(ArrayList<Resource> resource) {
ArrayList<Subject> subjects;
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier().getURL());
subjects = resource.getSubjects();
for (int i=0; i < subjects.size(); ++i) {
System.out.println(subjects.getCategory() + " :: " + subjects.getSubcategory());
}
System.out.println();
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}
Let me know if I'm misinterpreting things, but if all you're looking for is a way to convert a primitive array into an ArrayList then I would use the following:
arrayList = Arrays.asList(array);
I'm a new java developer, and I want to develop my code with reflection.
I have a class call User:
I want to pass dynamic value to those 3 methods, so in java reflection I got some code but I don't understand why?
import .....
public class user
{
private int id;
private String name;
private Date dob;
public setID(int id)
{
this.id = id;
}
public setName(String name)
{
this.name = name;
}
public setDOB(Date dob)
{
this.dob = dob;
}
}
Class cls = Class.forName("user");
Method[] methods = cls.getDeclearedMethod();
for(Method m : methods)
{
Object[] args = new Object[1];
args[0] = .....
m.invoke(cls, args[0]);
}
I don't dare to ask why you wanna do this... this way but i hope this example helps you get the feeling of some of the capabilities of reflection provided by Java.
import java.lang.reflect.Method;
import java.util.Date;
public class Ref {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Class cls = Class.forName("User");
Object o = cls.newInstance();
Object[] fieldValues = { new Integer(1), "", new Date() };
Method[] methods = cls.getDeclaredMethods();
for (Method m : methods) {
Class[] paramTypes = m.getParameterTypes();
Object[] paramValues = new Object[1];
if (paramTypes.length == 0) {
continue;
}
if (paramTypes[0].equals(Date.class)) {
paramValues[0] = new Date();
} else if (paramTypes[0].equals(String.class)) {
paramValues[0] = "nice";
} else if (paramTypes[0].equals(Integer.TYPE)) {
paramValues[0] = 2;
}
if (paramValues[0] != null) {
try {
m.invoke(o, paramValues[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end for
} // end for
System.out.println("o = " + o);
} // end method main
} // end class Ref
class User {
private int id;
private String name;
private Date dob;
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDOB(Date dob) {
this.dob = dob;
}
public String toString() {
return "[id = " + id + ", name = " + name + ", date = " + dob + "]";
}
}