I want to have a method invokeProcessingMethod(String name, Object... args) that invokes a method from Processing and returns any value that may result.
I already have a method invokeMethod(String name, Object...args) that invokes a method from a superclass on the current instance, so I thought an implementation of this would be create a sketch with the method I already have
class ProcessingRELP extends PApplet{
public static void main(String[] args) {
PApplet.main("ProcessingRELP");
}
void settings(){
}
void setup() {
}
void draw() {
}
invokeProcessingMethod(String name, Object... args) {
invokeMethod(name, args);
}
}
and then do something like
class Test {
public static void main(String[] args) {
ProcessingRELP sketch = new ProcessingRELP();
Object data = sketch.invokeProcessingMethod("textWidth", "hello");
}
}
but I get the following exception because I am not invoking the Processing method in setup or draw
Exception in thread "main" java.lang.NullPointerException
at processing.core.PApplet.textWidth(PApplet.java:12960)
at ProcessingRELP.invokeProcessingMethod(ProcessingRELP.java:27)
at Test.main(Test.java:25)
Is there anyway to invoke a Processing method outside the sketch or a creative way to still do it in the sketch but be able to retrieve the data from outside the sketch?
You need to run the sketch first, because you are trying to invoke methods that depend on the runtime of the sketch (textWidth() uses the textFont and textSize of a live sketch in its calculation) and not static methods. Simply instantiating a ProcessingRELP object will not run it; this can be done with the following:
ProcessingRELP sketch = new ProcessingRELP();
PApplet.runSketch(new String[]{"--location=0,0", ""}, sketch);
Now you are able to call your method since the sketch is running.
I don't know of a way to initialize a Processing sketch in a way that gives you a reference to it. You need to use the PApplet.main() function:
String[] appletArgs = new String[] { "MySketch" };
PApplet.main("ProcessingRELP");
Shameless self-promotion: here is a tutorial on using Processing as a Java library.
On top of that, I would be very suspicious of your invokeMethod() approach. Why can't you just invoke the function directly?
Something like this:
float stringWidth = sketch.textWidth("hello");
Either way, I think you're going to need to refactor your code to use the PApplet.main() function instead of assuming you have a reference to the sketch itself.
You could do something like move your logic into the setup() function of your sketch class. But either way, your Processing sketch needs to be the entry point.
Related
This a much simplified version of my multithreading project and its just a way to replicate the issue in a simpler way for easy understanding.
So I have two classes startSession.java and main.java
what I am trying to do is to send a variable from startSession.java to main.java and Im also using multithreading. However, the problem I am facing is that everytime I try to retrieve the variable inside main I get a null value.
Inside startSession theres the run method and Setter(setSessionKey(String sess)) and getter(getSessionKey()) methods. I hardcoded a variable to test.
The get method only works inside the run method but when I call getSessionKey() from inside main I get a null as seen below. However, this is only a problem when I am using multithreading. When I dont use multithreading and instead just call the run method from inside main, the variable Im looking for is no longer null.
My question is there a way to send a variable from startSession to main while using multithreading ?
thank you
startSession.java
public class startSession extends Thread {
static String sessionKey;
public void run() {
String createdSession = "83248329";
setSessionKey(createdSession);
System.out.println("Inside run method: " + getSessionKey());
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sess) {
sessionKey = sess;
}
}
main.java
package com.Server;
public class Main {
static String session;
public static void main(String[] args) throws InterruptedException {
startSession startSession = new startSession();
startSession.start();
session = startSession.getSessionKey();
System.out.println("Inside Main: " + session);
}
}
with multithreading
without multithreading
Use a BlockingQueue whereby the Thread (Producer) will add to the shared queue and the Main (Consumer) will block on the take
main
public static void main(String[] args) throws Exception {
// example only uses 1024 - check what is best for you
BlockingQueue queue = new ArrayBlockingQueue(1024);
StartSession producer = new StartSession(queue);
....
System.out.println(queue.take());
startSession
String createdSession= "83248329";
queue.add(createdSession);
see https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html
and
https://jenkov.com/tutorials/java-util-concurrent/blockingqueue.html
class B {
public static void main(String[] args) {
}
}
class A {
public static void main(String[] args) {
B.main(args);
}
}
In the above flow, my init method is A.main which in turn calls B.main.
I know calling A.main will spawn a JVM. Does calling B.main inside A.main spawn another JVM?
OR
B.main is JUST another static method once a JVM is started on A.main as init function.
Option 2. The mains are just static methods of each class, and only one JVM is running when making the call from A to B.main(args).
You can also make use of this in JUNIT tests to help check the command line launch behaves as expected, such as
#Test void coverage() {
A.main(new String[] { "a","b" }); // or B.main
// assertions here if there is some output state you could check
}
I know this is a bit naive question but I want to understand the basic working principle behind multi-threading in java. Consider the following code and say A is executed in Main thread and it starts execution of another worker thread ,defined in class B. I want to know that can B.func1 called from A and run method of B, be executed in parallel or not?
public class A {
public static void main(String[] args) {
B obj = new B();
obj.start();
obj.func1();
}
}
public class B extends Thread {
public B() {
//constructor
}
public void run() {
while(true) {
//do somethings
}
}
public void func1() {
//do someotherthings
}
}
There is no magic behind a method call. If you call method from a thread, it is called in exactly the same thread. So since obj.func1() is called from main, it will be run in the main thread. It doesn't matter which class it belongs to or whether or not it extends Thread.
The new thread starts by executing run. Everything called from run and so on will be executed in parallel to main.
It's important to understand the difference between a thread and a Thread.
A thread is an independent execution of your code. Often when we talk about how some method or another works we say things like, "It tests the variable x, and if x is less than zero it calls the foobar method..."
Ok, but what is the "it" in that sentence? It is not the method. Methods don't do anything. A method is just a list of instructions, like the list of chores that somebody left for their housemate to perform. The list doesn't do the chores, it's the housemate that does the work (or so we might hope).
The "it" is a thread. Threads are entities in the operating system that execute methods (i.e., they do the chores).
A Thread, on the other hand, is a Java object that your program can use to create and manage new threads. Your program creates a new Thread object by doing:
thread t = new Thread(...);
[Oops! See what I just did? It's not your program, that does the work, it's your program's main thread, or maybe some other thread in your program. It's an easy thing to forget!]
Anyway, it subsequently creates the new thread by calling t.start();
Once you understand all that, then Sergey Tachenov's answer becomes obvious: Calling the methods of a Thread object really is no different from calling methods of any other kind of object.
There are multiple issues with your code. I have corrected them and added one more statement to print Thread Name in func1().
Working code:
public class A {
public static void main(String args[]){
B obj = new B();
obj.start();
obj.func1();
}
}
class B extends Thread{
public B (){
//constructor
}
public void run(){
while(true){
//do somethings
}
}
public void func1 (){
//do someotherthings
System.out.println("Thread name="+Thread.currentThread().getName());
}
}
output:
Thread name=main
Since you are directly calling func1() from main method (A.java) , you will get Thread name = main in output.
If you add same print statement run() method, you will get output as : Thread name=Thread-0
If I want to just test a block of Java code, is there a way to run it without putting it in a function?
Public static void main(String[] args){
//block of code
}
Also, how do I execute a static block of code like below?
static {
//block of code
}
You can create static blocks
public class StackOverflowUser {
public static StackOverflowUser god;
static {
god = new StackOverflowUser("Jon Skeet");
}
//Stoof
}
Which will do something (hopefully) at some point during the program's life span. The truth is, there's no telling when it fires, and it's not well documented and may change from JVM to JVM. It will definitely have fired before you make the first call to that class, but it could have been executed any time between right before your call and JVM init.
You can also create just constructor blocks
public class StackOverflowUser {
private static ArrayList<StackOverflowUser> users = new ArrayList<StackOverflowUser>();
{
users.add(this);
}
//Stoof
}
This will activate before the constructor is called, right before. Basically, right after object creation, but before initialization. Don't try messing with too many fields, because they won't have been set.
In terms of order, all blocks work the same way. Once the first block has been called, the second block, third block, etc. will all follow, as Jayan puts it "in textual order".
Static blocks get executed once the class is loaded or initialized. So if you want to test the code inside the static block, the best way is to create an instance of the class.
if you want to test your code the best way is to use some testing framework like JUnit or testng.
static block will be executed when your class is being loaded first. So it can be used for DB instantiation etc. where you are sure that this block will be executed before your other code run.
simple block {...} will run when you try to create an instance.
Here first this block will be called then the code written below your line containing new keyword will be called.
public class Test3 {
public static void main(String[] args) {
Test3 obj = new Test3();
}
{
System.out.println("hussain akhtar wahid");
}
}
public class StaticBlockTest {
/*
* Some Code Goes Here
*
* */
static {
System.out.println(" Static Block Executed ");
System.exit(0);
}
}
Static block gets executed without the need for the main method and you need to pass the System.exit(0) to terminate the currently running Java Virtual Machine to exit the program execution.
I have a class called LinkGroup which holds some game objects. I call Rotate to set some rotation variables for these objects. Whenever my game hits its update loop, I rotate the objects according to the rotation variables. If they've rotated enough, I fire an onComplete callback.
The following code works...
public void Rotate(){
_currentRotation = _0;
_targetRotation = 180; //degrees
_rotationSpeed = 50;
try{
_onComplete = LinkGroup.class.getDeclaredMethod("rotateComplete", null);
}
catch(Exception ex){
}
}
...but this is ugly.
I don't like having to declare the method rotateComplete and manually link it to Rotate via a string. Is there something similar to anonymous functions in C# so I can just declared the rotateComplete method inside the Rotate method?
For bonus points, is there a better way to implement the required exception handling for "getDeclaredMethod"? Terseness is a preference.
From my understanding, I believe you are trying to call onRotateComplete() method in the LinkGroup class whenever some game object is been rotated. You can use the pattern that Java Swing uses for handling button clicks or other events: This could be done this way:
Define an interface
interface IRotateHandler {
public void onRotateComplete();
}
Change the Rotate() to Rotate(IRotateHandler handler) and then in LinkGroup class you can call your game object like this.
gameObject.Rotate(new IRotateHandler() {
public void onRotateComplete() {
/* do your stuff!
}
}
You don't need to use getDeclaredMethod. Just make _onComplete be a Runnable (or something similar), and create an anonymous class:
public void Rotate(){
_currentRotation = _0;
_targetRotation = 180; //degrees
_rotationSpeed = 50;
_onComplete = new Runnable() {
public void run() {
rotateComplete();
}
};
}
Java 7 doesn't yet have closures. Java 8 will. So, for the time being, there's no way to write that function anonymously in Java.
As for the error handling, a quick glance at the API shows me that you throw two RuntimeExceptions and a ReflectiveOperationException. Catching Exception may be your best bet, unless you wanted to catch all three of these possible exceptions differently, and take different action based on each.