How can i call registerAudioPortUpdateListener?
I succeeded to call a hidden function.
But, in this situation i need to call a function with hidden inner interface as parameter.
public class AudioManager {
/**
* Listener registered by client to be notified upon new audio port connections,
* disconnections or attributes update.
* #hide
*/
public interface OnAudioPortUpdateListener {
/**
* Callback method called upon audio port list update.
* #param portList the updated list of audio ports
*/
public void onAudioPortListUpdate(AudioPort[] portList);
/**
* Callback method called upon audio patch list update.
* #param patchList the updated list of audio patches
*/
public void onAudioPatchListUpdate(AudioPatch[] patchList);
/**
* Callback method called when the mediaserver dies
*/
public void onServiceDied();
}
/**
* Register an audio port list update listener.
* #hide
*/
public void registerAudioPortUpdateListener(OnAudioPortUpdateListener l) {
sAudioPortEventHandler.init();
sAudioPortEventHandler.registerListener(l);
}
}
Can you try this code , for me it is working in java,
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import de.apps.io.AudioManager;
public class Application {
public static void main(String[] args) {
System.out.println("hello world");
Class someInterface1 = null;
try {
// someInterface = AudioManager.class.getDeclaredClasses();
someInterface1 = Class.forName("de.apps.io.AudioManager$OnAudioPortUpdateListener");
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(someInterface);
System.out.println(someInterface1);
Object o = Proxy.newProxyInstance(someInterface1.getClassLoader(), new java.lang.Class[] { someInterface1 }, new Handler());
AudioManager manager = new AudioManager();
Method me = null;
try {
me = manager.getClass().getMethod("registerAudioPortUpdateListener", new java.lang.Class[] { someInterface1 });
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
me.invoke(manager, o);
} 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();
}
System.out.println(me);
}
static class Handler implements InvocationHandler
{
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String method_name = method.getName();
Class<?>[] classes = method.getParameterTypes();
System.out.println("called " + method_name);
return null;
}
}
}
Related
I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.
I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?
kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
try {
HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";
System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("\n"+sonuclariYazdir(test,0));
} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).
Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).
Read this tutorial: Concurrency in Swing
What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).
Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.
Try using swing worker in your method.
Swing Worker
Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:
import javax.swing.SwingUtilities;
/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{
private Object value; // see getValue(), setValue()
private Thread thread;
/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{
private Thread thread;
ThreadVar(Thread t)
{
thread = t;
}
synchronized Thread get()
{
return thread;
}
synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;
/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}
/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}
/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();
/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}
/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}
/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* #return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{
public void run()
{
finished();
}
};
Runnable doConstruct = new Runnable()
{
public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}
Then add your logic inside:
SwingWorker worker = new SwingWorker() {
#Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...
return 0;
}
};
worker.start();
So the end resuld should look like this (Note that this is untested code):
kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingWorker worker = new SwingWorker() {
#Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
try {
HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";
System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("\n"+sonuclariYazdir(test,0));
} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});
Here is my classes.
package com.psu.janibot;
public class Janibot implements Runnable {
public void move() {
System.out.println("move");
}
#Override
public void run() {
}
// main method
public static void main(String[] args) {
try {
Janibot janibot = (Janibot) Class.forName("Janitor").newInstance();
janibot.run();
} 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();
}
}
}
import com.psu.janibot.Janibot;
public class Janitor extends Janibot {
public void run() {
move();
}
}
package com.psu.janibot;
public class Janitor2 extends Janibot{
public void run() {
move();
}
}
if i type >java Janitor it will run the Janitor class
if i type >java Janitor2 it will run the Janitor2 class
I want to do is to run Janitor or Janitor2 without typing the class name in forName method like this Janibot janibot = (Janibot) Class.forName("Janitor").newInstance();
Class.forName() takes a String as a parameter, so you need to pass it somehow, so I presume you mean not hard coded.
Pass the String in as the arguments to the program and read them from the args array
java Janibot Janitor
....
Class.forName(args[0]).newInstance()
Other options exist such as read from file, using a Scanner, etc.
I have an Activity Class Anmeldung, a normal java class thread_haupt.class and a Activity funktionen_haupt.class.
on Start of Anmeldung.class starts a function(funktionstarter) of threads_haupt.class
This calls a function from functionen_haupt.class via invoke.
The idea is to have a function that can start other functions also from other classes
the problem is java.lang.InstantiationException: can't instantiate class … no empty constructor in my thread_haupt.class when I try to newInstance() (see below in thread_haupt.class)
java.lang.InstantiationException: can't instantiate class … no empty constructor
Anmeldung.Class
public class anmeldung extends Activity implements OnClickListener{
#Override
protected void onStart() { // start ist dann aufgerufen wenn alles gebaut ist
// TODO Auto-generated method stub
meine_funktionen.buttons_vorbereiten(this);
/**
* hier wirde zuerst der spinner befüllt
*/
thread_haupt meinThread = new thread_haupt();
//HOMEPAGE,naj.nuz.wz.wa.dc.kommunikation.allgemein kommunikation,naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein helfer, Activity meineAct};
meinThread.meine_parameter= new Object[] {HOMEPAGE,kommunikation,helfer,meineAct};
meinThread.meine_funktion="staedte_abfragen";
meinThread.mein_context=this.getApplicationContext();
meinThread.meine_activity=this;
meinThread.thread_starten("staedte_abfragen"); // HERE !!!
threads.class
public class thread_haupt {
public Object[] meine_parameter;
public String meine_funktion;
public Object mein_context;
public Activity meine_activity;
public allgemein mein_helfer = new allgemein();
public funktionen_haupt meine_funktionen = new funktionen_haupt((Context) mein_context, meine_activity);
/**
* hier sollen die threads gestartet werden
* #param threadName
*/
public void thread_starten(String threadName){
switch (threadName) {
case "staedte_abfragen":
//Thread thread = new Thread(new Runnable(){
//hier hab ich das gefunden http://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi
//public void run() {
//meine_funktionen.staedte_abfragen(HOMEPAGE,kommunikation,helfer, meineAct);
try {
meine_funktionen.funktionstarter("naj.nuz.wz.wa.dc.drinkcoffee.funktionen_haupt", meine_funktion, meine_parameter, mein_context);
// hier aufgehört dies startet nicht
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
//});
//thread.start();
break;
default:
break;
}
}
}
funktionen_haupt.class
public class funktionen_haupt extends Activity {
// CONTEXT empfangen von den die die klasse aufrufen
Context mContext;
Activity mActivity;
allgemein kommunikation = new allgemein();
naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein helfer = new naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein();
public funktionen_haupt(Context mContext,Activity mActivity){
this.mContext = mContext;
this.mActivity=mActivity;
}
public void funktionstarter(String package_name,String funktion_name,Object[] arguments, Object meincontext) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, java.lang.InstantiationException {
//no paramater
Method[] methoden;
Class cls = null;
Object obj = null;
try {
cls = Class.forName(package_name);
obj = cls.newInstance(); // !!! HERE IS MY PROBLEM !!!!
//Constructor<funktionen> obj = cls.getConstructor(cls);
//funktionen dieklasse = obj.newInstance(null);
//Object obj = FactoryRegistry.getFactory(cls).newInstance();
methoden = cls.getDeclaredMethods();
for (int i =0;i<=methoden.length-1;i++){
if (methoden[i].getName().equals(funktion_name)){
Method method2 =cls.getDeclaredMethod(funktion_name, methoden[i].getParameterTypes());
if (meincontext==null){
method2.invoke(obj, arguments);
}
else{
method2.invoke(meincontext, arguments);
}
break;
}
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
methoden = cls.getDeclaredMethods();
for (int i =0;i<=methoden.length-1;i++){
if (methoden[i].getName().equals(funktion_name)){
Method method2 =cls.getDeclaredMethod(funktion_name, methoden[i].getParameterTypes());
method2.invoke(this, arguments);
break;
}
}
}
}
I get an exeption by
cls = Class.forName(package_name);
obj = cls.newInstance(); // java.lang.InstantiationException: can't instantiate class … no empty constructor
and I don´t know why.
Can somone tell me whats wrong, why it´s not working and what I doing wrong ?
Thanks in advance.
Because you declared a constructor with different parameters, the default (empty) constructor is gone. The default constructor is only available when you have not defined another constructor.
You can create an empty constructor like this:
public funktionen_haupt(){
}
public funktionen_haupt(Context mContext,Activity mActivity){
this.mContext = mContext;
this.mActivity=mActivity;
}
If you want to create the object with the parameters then you should not use the newInstance() method but just call the constuctor.
I'm making a kind of test program to be able to override methods in classes for an api I'm making in java but I'm getting a weird error when trying to invoke a method from another class...
Here is the main "component class":
package st.cmp;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Component {
public class Overrider{
Class<?> source;
Class<?>[] overs;
String name;
public Overrider(Class<?> s,String n,Class<?>[] o){
source=s;
overs=o;
name=n;
}
public Object call(Object[] param){
try {
return source.getMethod(name, overs).invoke(this, param);
} catch (NoSuchMethodException | SecurityException 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();
}
return null;
}
};
public HashMap<String,Component> cmps;
public HashMap<String,Overrider> over;
public Component(){
cmps=new HashMap<String,Component>();
over=new HashMap<String, Overrider>();
}
public void registerComponent(String nm,Component cm){
cmps.put(nm,cm);
}
public Component getComponent(String nm){
return cmps.get(nm);
}
public void override(Class<?> cl,String name,Class<?>[] param){
over.put(name,new Overrider(cl,name,param));
}
public Object call(String mnm,Object[] a){
Overrider ov=over.get(mnm);
if(ov!=null){
ov.call(a);
}
Class<?>[] abc=new Class<?>[a.length];
for(int i=0;i<a.length;i++){
abc[i]=a[i].getClass();
}
try {
return this.getClass().getDeclaredMethod(mnm, abc).invoke(this,a);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e) {
// TODO Auto-generated catch block
try {
this.getClass().getDeclaredMethod(mnm, abc).invoke(this,a);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}
public void test(String a){
System.out.print(a);
}
public int add(Integer a,Integer b){
return a+b;
}
}
And this is the main class:
package st;
import st.cmp.Component;
public class Start {
public static void main(String[] args)
{
new Start().start();
}
public void start(){
Component a=new Component();
a.call("test",new Object[]{a.call("add",new Object[]{1,5}).toString()});
a.override(this.getClass(), "add", new Class<?>[]{Integer.class,Integer.class});
a.call("test",new Object[]{a.call("add",new Object[]{1,5}).toString()});
}
public int add(Integer a,Integer b){
return a*b;
}
}
I'm getting this error when I start the program:
6java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at st.cmp.Component$Overrider.call(Component.java:22)
at st.cmp.Component.call(Component.java:64)
at st.Start.start(Start.java:16)
at st.Start.main(Start.java:8)
6
Can anyone help me?
it says "object is not an instance of declaring class"... But what "object" is it refering to?
In your Start class, you are calling the Component.override() method:
// v--- This is the Class Object
a.override(this.getClass(), "add", new Class<?>[]{Integer.class,Integer.class});
Where a is of type Component. You are passing it this.getClass(), which is a Class object for Start. Then in override():
// v--- Class object gets passed along here
over.put(name,new Overrider(cl,name,param));
You are creating a new Overrider, and giving the Class object for Start to the constructor, which sets the Class<?> source; field to the Start Class object. Then when you call the Overrider.call() method, it does this:
// v--- and finally invoked here
return source.getMethod(name, overs).invoke(this, param);
And passes invoke() a this which is an instance of Component, while source is a Class object for Start. In this line, "source" and "this" need to be the same class, but Start and Component aren't.
Your code is quite convoluted, but this my help. If you have a line like this:
klass.getMethod(name).invoke(obj)
then the error says that obj is not an instance of klass.
I have a Java GUI application from which another java GUI application is invoked using reflection and loading. It works fine the only problem faced is, on closing the JFrame of invoked application the Main GUI application frame also closes. How can I prevent the main application (frame) from closing??
I cannot change the defaultCloseOperation of the invoked application, However a change to the main application can be made. Does it have any thing to do with threads??
This is my applications code that executes a target application
public class ClassExecutor{
private ClassLoaderOfExtClass classLoader;
private byte[][] ArrayOfClasses;
private String[] ArrayOfBinaryNames;
#SuppressWarnings("rawtypes")
private ArrayList<Class> loadedClasses;
private ArrayList<String> loadedClasesNames;
private Object[] parameters;
#SuppressWarnings("rawtypes")
public ClassExecutor() {
classLoader = new ClassLoaderOfExtClass();
new ArrayList<Class>();
loadedClasses = new ArrayList<Class>();
loadedClasesNames = new ArrayList<String>();
}
#SuppressWarnings("unchecked")
public void execute(File[] file, String[] binaryPaths) {
Object[] actuals = { new String[] { "" } };
Method m = null;
try {
Field classesx=ClassLoaderOfExtClass.class.getDeclaredField("classes");
classesx.setAccessible(true);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
/*for (int i = 0; i < file.length; i++) {
for (int j = 0; j < file.length; j++) {
try {
#SuppressWarnings("rawtypes")
Class c = classLoader.loadClassCustom(file[i], binaryPaths[i]);
//Fied classex=classLoader.getResource("classes");
}catch(Exception e){
}
}
}
Class<?>[]classesxx= getLoadedClasses(classLoader);
System.out.println("Loaded classes have size "+ classesxx.length);*/
for (int i = 0; i < file.length; i++) {
try {
#SuppressWarnings("rawtypes")
Class c = classLoader.loadClassCustom(file[i], binaryPaths[i]);
try {
if (c.getMethod("main", new Class[] { String[].class }) != null) {
m = c.getMethod("main", new Class[] { String[].class });
} else {
System.out.println("This class does not contain main");
continue;
}
} catch (NoSuchMethodException e) {
// System.out.println("Main not found!!!");
// System.out.println("M here");
// e.printStackTrace(); // not printing stack trace
} catch (SecurityException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("No such class definition exist!!");
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
try {
m.invoke(null, actuals);
// CallStack.print();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(ArrayList<byte[]> stuffedFiles,
ArrayList<String> binaryPaths) {
convertToArray(stuffedFiles, binaryPaths);
loadAllClasses(ArrayOfClasses, ArrayOfBinaryNames);
Object[] actuals = { new String[] { "" } };
Method m = null;
/*
* Method[] m1= new Method[10]; for (Class c : loadedClasses) {
* m1=c.getMethods(); } for(Method m2: m1){
* System.out.println(m2.getName()); }
*/
/* System.out.println(loadedClasses.size()); */
for (Class c : loadedClasses) {
/*
* System.out.println(c.toString());
* System.out.println(c.getConstructors());
*/
// for (int i = 1; i < file.size(); i++) {
/*
* for(Method meth : c.getMethods()){ meth.setAccessible(true);
*
* }
*/
try {
if (c.getMethod("main", new Class[] { String[].class }) != null) {
m = c.getMethod("main", new Class[] { String[].class });
break;
} else {
// System.out.println("This class does not contain main");
continue;
}
} catch (NoSuchMethodException e) {
System.out.println("Program does not contain main");
} catch (SecurityException e) {
e.printStackTrace();
}
}
try {
if(parameters==null){
m.invoke(null, actuals);
}
else{
try {
System.out.println("It Fails Here");
m.invoke(null, parameters);
} catch (Exception e) {
System.out.println("Illegal arguments");
}
}
// CallStack.print();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You'll want to use the DISPOSE_ON_CLOSE operation, so it would be setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
EXIT_ON_CLOSE would be the option that closes all windows which I believe is what you are currently experiencing.
You have the following options for the defaultCloseOperation:
DO_NOTHING_ON_CLOSE - The do-nothing default window close operation;
HIDE_ON_CLOSE - The hide-window default window close operation;
DISPOSE_ON_CLOSE - The dispose-window default window close operation.
EXIT_ON_CLOSE - The exit application default window close operation. Attempting to set this on Windows that support this, such as JFrame, may throw a SecurityException based on the SecurityManager. It is recommended you only use this in an application.
The Option DISPOSE_ON_CLOSE could be used in order to avoid to close all windows, closing just the one you want.
If you don't have direct access to JFrame object as you have with the last posted code, you could use Window.getWindows() in order to receive all windows instance (as JFrame is a Window too it will be listed too). And then set the defaultCloseOperation on that.
Possibly you will need to use threads because the defaultCloseOperation needs to be set after invoke main method.
Theoretically it works, so I think this is a good shot ;)
I am not allowed to make changes to the application being invoked.
That was a comment in reply to #JeffLaJoie just to clarify, it would not require any changes to the code of the other app., just an extra method call or two by your app. at run-time to set the close operation of the 3rd party frame.
Failing that, the best solution I can think of is to start the new frame in a separate Process that starts a new JVM, when the user closes the other app., it and the 2nd JVM will end, while leaving the original app. on-screen.