I am creating java files from json Objects using a library called jsonschema2pojo-core.jar. It successfully creates the required files for me. Now I need to access the newly(dynamically) created file and creates its instance to use it further.
But as the newly created class is still not in the classpath I am unable to do this. Tried to do my part of research and figured out that Eclipse jars allows such refresh only in plugin projects. Can anyone suggest some thing for this?
public static void main(String[] args){
String fileName = "MyJavaFile";
POJOBuilder pojo = new POJOBuilder();
pojo.buildPOJO("file:///C:/mypath/myJSON.json", fileName); //generates the java file MyJavaFile.java
Object obj = null;
try {
obj = Class.forName("com.mypackage."+fileName).newInstance(); // Java file not available yet
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can this be done through threads? I mean wait until the creation of the POJO is done and then start with the rest after that?
Related
I am trying to execute a function from a class in a jar file dynamically. I have the location of the jar file, the name of the class and the function in it as strings.
I looked at these questions, but none of the answers worked for me:
How should I load Jars dynamically at runtime?
ClassNotFoundException while trying to load class from external JAR at runtime
How to load a jar file at runtime
Dynamically load a jar
Load jar dynamically at runtime?
Here is what I've got so far:
In the main program:
public class Main
{
public static void main(String[] args)
{
File file = new File("E:\\DeSKtop\\hw.jar");
String lcStr = "Main1";
URL jarfile;
try {
jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Method method = loadedClass.getDeclaredMethod("returnHW");
Object instance = loadedClass.newInstance();
Object result = method.invoke(instance);
//System.out.println(method.invoke());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(loadLibrary(myJar));
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In the jar file I'm trying to load:
public class Main1 {
public static void main(String[] args)
{
}
public static String returnHW()
{
System.out.println("HlloWOrld");;
return "Hello Wrld!";
}
}
When I try to run the main program I get this:
java.lang.ClassNotFoundException: Main1
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.net.FactoryURLClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at Main.main(Main.java:22)
Can you tell me what I'm doing wrong? Thank you in advance.
the solution is that you have to state the packages as well.
If you update your variable lcStr where you store the classname to include the package, it shall work.
Example:
String lcStr = "com.company.Main1";
I want to rename a csv file in java using following code segment, but file is not getting renamed.
public static void main(String[] args) {
File fileToBeRenamed = new File("C:/abc/a.txt");
File newFileName = new File("C:/abcd/b.txt");
try {
fileToBeRenamed.createNewFile();
newFileName.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean isRenamed = fileToBeRenamed.renameTo(newFileName);
if(isRenamed)
System.out.println("File renamed successfully");
else
System.out.println("File could not be renamed");
}
Its not throwing any error. but file is not getting renamed.So please help me to do so.
let's suppose you have a file A(fileToBeRenamed) and you want to rename it to B(newFileName). Then , no need to create "newFileName" file. your code is fine , except the file creation part.
so comment out the lines:
try {
fileToBeRenamed.createNewFile();
newFileName.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And it will work.
Note: I don't think it has anything to do with file extension(csv/text etc), when both are the same.
I think you want to rename a.txt to b.txt, So you don't need create b.txt. If you remove newFileName.createNewFile() will work
I want to create a messaging application for Android, so I've been reading up about XMPP and Asmack.
Asmack sounds pretty much exactly what I want, especially after reading this other question - Android and XMPP: Currently available solutions.
However, I'm fairly new to Android programming and also Github.
I have found the src for Asmack at https://github.com/Flowdalic/asmack, and also downloaded the jar from http://asmack.freakempire.de/4.0.4/, which I have included in my project. However I am unsure how the folders in the github asmack folder are supposed to be used. After hours trawling google trying to find some sort of step by step guide on how to set aSmack up, and not finding anything useful, I'm losing the will to live!
I'm using the following example code I found on the Smack github page, and I dont get any errors:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
XMPPTCPConnection connection = new XMPPTCPConnection("jabber.org");
try {
connection.connect();
connection.login("mtucker", "password");
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Chat chat = ChatManager.getInstanceFor(connection)
.createChat("jsmith#jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
chat.sendMessage("Howdy!");
} catch (NotConnectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
However I haven't used the 'build environment' from aSmack github repository - how is this meant to be included/used?
Thanks for any help!
You need to add single Jar file (last version now is 4.0.6) to your library and also don't forget to set proper permissions in manifest file.
This is probably a very silly way to go about things, but say we had a class with lots of Fields that were components, how would one go about adding them in a for each loop with reflection?
Here is what I've tried so far (though it is obviously doomed to fail):
for(Field bits: this.getClass().getDeclaredFields()){
try {
this.add((Component)Class.forName(bits.getName()).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Each of the fields is not a class so doing the above will not work, but I have defined what they are, and they should exist at runtime.
How should I be doing this?
You try to create a class from a field name, so it won't work.
bits.getName() returns something like "myHelloWorldLabel" and not javax.swing.JLabel.
You can either add the value of the field bits.get(this) or create a new object from the class bits.getDeclaringClass().newInstance().
I would also add a check that the class extends JComponent.
I am attempting to load the corresponding hashmap using reflection. However I get a field not found exception. Please let me know what you think the issue is. Thanks
//Find the map
HashMap<String, Matches> map = null;
//Reflection to find the appropriate map
try {
Field field = Field.class.getField(mapName); //exception (mapname = lookupHashmap) this class has a lookupHashmap declared)
try {
//Set the map
map = (HashMap<String, Matches>)field.get(this); //Not sure if this is correct
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Stack trace
java.lang.NoSuchFieldException: majorFieldLookup
at java.lang.Class.getField(Class.java:1522)
at MatchingGraph.getResultsForMap(MatchingGraph.java:245)
at MatchingGraph.getmajorFieldMatches(MatchingGraph.java:196)
at Matcher.findMatches(Matcher.java:95)
at Tester.main(Tester.java:27)
You do not want Field.class.getField(mapName);
You want to use whatever class it is you have the map on, call it 'MyClass'
Field field = MyClass.class.getDeclaredField(mapName);
Edit: changed to getDeclaredField(...) from getField(..) because the field was private.
#Rolfl solved your problem i guess.
And I'm suggesting Apache Commons BeanUtils.
And use the method
BeanUtils.copyProperties(source, target);
http://commons.apache.org/proper/commons-beanutils/