Dynamic method call needs reflection class?
Hi,
First of all, this is my first post so go easy on me ;)
I would like to have something like this in Java:
String name = "number1";
int temp = name + getme();
the integer temp should now be the result of the method "number1getme()".
By changing the value of 'name' I could get the value of number2, number3 etc. etc.
Hope you understand and can help.
Yours Sincerely,
GrandiJoos
If you really want to do it this way, you will indeed need to use reflection. Have you considered other options, such as storing values in a Map or creating one getme() method that takes a name argument?Map<String, Integer> temps = new HashMap<String, Integer>();
.. fill the map with temperatures
String name="number1";
int temp = temps.get(name);orString name="number1";
public int getme(String name) {
int result = ...;
if(name.equals("number1")) {
result = <some temp here>;
return result;
}
Similar Messages
-
Dynamic method calls in bounded task flows?
Hi!
I have the following scenario:
We are developing a framework in which we would include modules as ADF libraries (as JAR files) with bounded task flows. This framework contains a bean class with bindings for some UI components in framework which I enable or disable (depends on user action). That is the main reason bean class should be present in framework application.
I have a bounded task flow in every module which needs to call a method in bean with UI component's bindings that would enable or disable that component.
How can I achieve that? To pass bean as a parameter into bounded task flow and then call its methods? That is dynamic method calls for bean.
I'm using JDeveloper 11.1.2.1.0
Thanks for your help
Regards, MarkoHi,
I explained this; +"I have a bounded task flow in every module which needs to call a method in bean with UI component's bindings that would enable or disable that component. How can I achieve that? To pass bean as a parameter into bounded task flow and then call its methods?"+ a couple of times already (not sure if it was all for you) and don't think I change my position here. I also explained how to use a ValueExpression to lookp a managed bean containing component bindings (should be in requestscope).
Frank -
Type conflict during dynamic method call.
While executing the following program I get the error "Type conflict during dynamic method call.":
DATA: container_r TYPE REF TO object,
grid_r TYPE REF TO object,
itab_saplane TYPE TABLE OF saplane.
* IMPORTANT NOTE: class names must be in UPPER CASE
DATA: str_cnt TYPE seoclsname VALUE 'CL_GUI_CUSTOM_CONTAINER',
str_gui TYPE seoclsname VALUE 'CL_GUI_ALV_GRID',
meth_name TYPE STRING VALUE 'SET_TABLE_FOR_FIRST_DISPLAY'.
TYPE-POOLS abap.
DATA: ptab TYPE abap_parmbind_tab,
wa_ptab LIKE LINE OF ptab,
ref TYPE REF TO data.
CREATE OBJECT container_r TYPE (str_cnt)
EXPORTING container_name = 'CUSTOM_CONTROL1'. " Name of the custom control area (UC!)
* Construct parameter itab
GET REFERENCE OF container_r INTO ref.
wa_ptab-name = 'I_PARENT'. " Must be upper-case
wa_ptab-value = ref.
INSERT wa_ptab INTO TABLE ptab.
* EXPORTING i_parent = container_r.
CREATE OBJECT grid_r TYPE (str_gui)
PARAMETER-TABLE ptab.
SELECT * FROM saplane INTO CORRESPONDING FIELDS OF TABLE itab_saplane.
* Cannot call set_table_for_first_display directly...
CALL METHOD grid_r->(meth_name)
EXPORTING I_STRUCTURE_NAME = 'SAPLANE' " Type of the rows in the internal table (UC!)
CHANGING IT_OUTTAB = itab_saplane. " The internal table itself
CALL SCREEN 100.
Any help would be appreciated!Hi ...
Apologies ... for confusion ... actually both are required ...
the type 'E' as well as CL_GUI_CONTAINER.
The below code worked for me ...
check out how I cast it to the parent class type ...
DATA : lv_container TYPE seoclsname VALUE 'CL_GUI_CUSTOM_CONTAINER',
lv_control TYPE seoclsname VALUE 'CL_GUI_ALV_GRID',
lv_method TYPE string VALUE 'SET_TABLE_FOR_FIRST_DISPLAY',
lt_par_tab TYPE abap_parmbind_tab,
ls_param LIKE LINE OF lt_par_tab,
lref_cont TYPE REF TO cl_gui_container,
lv_data TYPE REF TO data.
CREATE OBJECT lref_container
TYPE
(lv_container)
EXPORTING
container_name = 'ALV_AREA'.
ls_param-name = 'I_PARENT'.
ls_param-kind = 'E'.
lref_cont ?= lref_container.
GET REFERENCE OF lref_cont INTO lv_data.
ls_param-value = lv_data.
INSERT ls_param INTO TABLE lt_par_tab.
** Now create ALV Control.
CREATE OBJECT lref_alv_ctrl
TYPE
(lv_control)
PARAMETER-TABLE
lt_par_tab.
** Set table for 1st display
DATA : lv.
lv = lref_alv_ctrl->mc_fc_print.
CALL METHOD lref_alv_ctrl->(lv_method)
EXPORTING
i_structure_name = 'T001'
CHANGING
it_outtab = lt_company.
Cheers
Edited by: Varun Verma on Aug 12, 2008 4:19 PM -
Setting breakpoint on any method call of a class
Using the new (or old) debugger, is it possible to set a breakpoint that will stop on any method invocation of a class?
I am debugging the processing of a purchase order and want the debugger to stop on any method call to CL_PO_HEADER_HANDLE_MM, which has 113 methods, so setting a breakpoint in each method is way too tedious.
Do you know of a way to do this in one go?Activate Layer-Aware Debugging for class CL_PO_HEADER_HANDLE_MM, and then set breakpoint on statement CALL METHOD.
I tried for CL_GUI_ALV_GRID, and it worked. I am on 702 release. -
Dynamic Method call with CHANGING
Hi,
I have the following method call:
CALL METHOD o_salv->DISPLAY_SALV
CHANGING
it_data = it_ekko.
I would like to make this dynamic so that I can call it multiple times from my program with the came set of code.
I have this working for other Method calls, but the use the same parameters on both sides such as:
CALL METHOD o_main->get_date
IMPORTING
it_ekko = it_ekko.
being coded as such:
CALL METHOD o_main->(v_method)
PARAMETER-TABLE
ptab.
Can someone please give me some guidance on how to code the top example dynamically when the 2 variables are different?
Hope that makes sense...thanks for your help!
AndyHello Bjorn
I would suggest the following approach:
(1) Collect all your GUI control instances in an itab whose line type is TYPE REF TO cl_gui_control.
(2) Define your "free" method:
LOOP AT mt_gui_controls INTO lo_gui_control.
* See if gui control was text editor
TRY.
lo_textedit ?= lo_gui_control.
CATCH cx_sy_move_cast_error INTO lo_error.
ENDTRY.
IF ( lo_error IS NOT BOUND ).
lo_textedit->free.
* ... your coding
CONTINUE.
ENDIF.
* See if gui control was tree
TRY.
lo_tree ?= lo_gui_control.
CATCH cx_sy_move_cast_error INTO lo_error.
ENDTRY.
ENDLOOP.
The FREE methods are redefined in the subclasses. However, you could try to call lo_gui_control->free directly because I am not sure if the coding of the superclass or subclass is called (I cannot test this at the moment).
Regards
Uwe -
Working with class based exception and dynamic method calls
Hi Gurus,
we just changed out ERP from EHP6 to EHP7.
Since we did so we are facing an issue with an Z-Report we are using quite often.
This reports looks up Workitems and executes the according methods so that we can go into debugging if we were facing any problems or errors.
since the EHP Upgrade this statement has problems:
data: lt_parmbind type abap_parmbind_tab, lt_excpbind type abap_excpbind_tab, lo_runtime type ref to object. call method lo_runtime->(iv_cls_method) parameter-table lt_parmbind exception-table lt_excpbind.this CALL METHOD Statement has Problem with the Exception Table. We are quite often getting DYN_CALL_METH_EXCP_NOT_FOUND short dumps with Exception "CX_SY_DYN_CALL_EXCP_NOT_FOUND".
The system has problems handling the content of lt_excpbind. if i clear this table the CALL METHOD statement works fine.
AS an example we are trying to call /IDXGC/CL_PD_PROCESS_STEPS-->CREATE_DATA. This method has 2 exceptions
/IDXGC/CX_PROCESS_ERROR
Process Layer Exception
CX_BO_TEMPORARY
Temporary Business Exception
The Content of LT_EXCPBIND is
INDEX
NAME
VALUE
2
/IDXGC/CX_PROCESS_ERROR
1
2
CX_BO_TEMPORARY
2
From my point of view the Problem ist, that they are marked as "class based". I think so because if you looked up the SAP Help for the EXCEPTION-TABLE Statement it is written that is statement only works for none-classbased exception.
I think that restriction is quiet clear. But what i am wondering about is.. that restriction also exists for EHP6. And in EHP6 it work. Does anyone know why? Or how i can change me CALL METHOD Statement that i will work again?
Best Regards
UdoClass-based exceptions must be caught using try/catch statement.
Calling dynamically a method catchable exceptions are:
CX_SY_DYN_CALL_EXCP_NOT_FOUND
CX_SY_DYN_CALL_ILLEGAL_CLASS
CX_SY_DYN_CALL_ILLEGAL_METHOD
CX_SY_DYN_CALL_PARAM_MISSING
CX_SY_DYN_CALL_PARAM_NOT_FOUND
CX_SY_REF_IS_INITIAL
Anyway catching cx_root (as shown by Matthias) will catch everything is catchable. -
Hello Gurus,
is there any possibility to write something like this in ABAP ??
CALL METHOD zz_but050=>get_but050
EXPORTING
IF X = 1. i_var_partner1 = l_var_partner1 ENDIF.
IF X = 2. i_var_partner2 = l_var_partner2 ENDIF.
IMPORTING
e_tab_but050 = l_tab_but050
EXCEPTIONS
keine_daten = 1.
Best regards,
Ioan Constantin.Yes there is. The simplest would be
data: lv_partner type ...
IF X = 1. lv_partner = l_var_partner1 ENDIF.
IF X = 2. lv_partner = l_var_partner2 ENDIF.
CALL METHOD zz_but050=>get_but050
EXPORTING
i_var_partner1 = lv_partner
IMPORTING
e_tab_but050 = l_tab_but050
EXCEPTIONS
keine_daten = 1.
Or you can use dynamic form of CALL METHOD where you pass your parameters by means of PARAMETER-TABLE addition. Please refer [CALL METHOD|http://help.sap.com/abapdocu_70/en/ABAPCALL_METHOD_SHORTREF.htm] -> dynamic form.
Regards
Marcin -
Dynamically calling a certain class
Hey all,
So I have some animated charts I have done up. They live in
my library and are linked with the names; "chart1", "chart2",
"chart3." If I want to add one of them to the stage based on a
selection by a user, how can I create a dynamic name call to the
class to add them. Instead of hard coding them, I want to insert
the number into the function. For example.
function createNewChart(myChart){
var newChart = new (this["chart"+myChart])()
addChild(newChart);
Of course that doesn't work, so I am looking for the syntax
to make it work. Ideas?
- BI knew it was out there. Thanks man.
-
i try run VS 2012 with /SafeMode. I create new empty Winform. When I start debug, I got:
"error while trying to run project uncaught exception thrown by method called through reflection"Hi Matanya Zac,
Did you restart your machine? How about installing the VS2012 update 4?
>>error while trying to run project uncaught exception thrown by method
Did you install the VS update in your VS IDE? I met this issue before which was related to the VS update:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5ead8ee9-ea09-4060-88b0-ee2e2044ff82/error-while-trying-to-run-a-project-uncaught-exception-thrown-by-method-called-through-reflection?forum=vsdebug
If still no help, I suggest you repair your VS, and then restart your machine, test the result.
Best Regards,
Jack
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Dynamic Call to Java Class or Method
Hi All,
I have a requirement to call a Class or a Method Within the same class dynamically based on the user choice. I will give an example with how I do it in pl sql.
begin
if (choice = 1) then
execute immediate 'package.procedure1(params)';
elsif (choice = 2) then
execute immediate 'package.procedure2(params)';
else
execute immediate 'package.procedure3(params)';
end if;
end;
From the Example above, I call a program based on user choice. How Can I do the same in Java?
Thank you.
Edited by: Eric S. on Jul 6, 2011 9:52 AMI have a requirement to call a Class or a MethodYou can call a method, but not the Class where as you can instantiate the Class.
I will give an example with how I do it in pl sql.
begin
if (choice = 1) then
execute immediate 'package.procedure1(params)';
elsif (choice = 2) then
execute immediate 'package.procedure2(params)';
else
execute immediate 'package.procedure3(params)';
end if;
end;
From the Example above, I call a program based on user choice. How Can I do the same in Java?The similar way. Here it takes the following structure.
ClassA object = new ClassA();
if(choice==1) {
object.callMethod1();
} else if(choice==2) {
object.callMethod2();
} else if(choice==3) {
object.callMethod3();
} Also you can switch case instead of if else. It takes the following structure.
ClassA object = new ClassA();
switch(choice) {
case 1: object.callMethod1(); break;
case 2: object.callMethod2(); break;
case 3: object.callMethod3(); break;
}I recommend you to go with the second one which using switch. -
Need help calling a method from an immutable class
I'm having difficulties in calling a method from my class called Cabin to my main. Here's the code in my main if(this is where i want my method hasKitchen() from my Cabin class)
System.out.println("There is a kitchen.");
else
System.out.println("There is not a kitchen.");
}and here's my method from my Cabin class:public boolean hasKitchen()
return kitchen;
}You should first have an instance of Cabin created by using
Cabin c = ....
if (c.hasKitchen()) {
System.out.println("There is a kitchen.");
} else {
System.out.println("There is not a kitchen.");
} -
How to access private method of an inner class using reflection.
Can somebody tell me that how can i access private method of an inner class using reflection.
There is a scenario like
class A
class B
private fun() {
now i want to use method fun() of an inner class inside third class i.e "class c".
Can i use reflection in someway to access this private method fun() in class c.I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
So here's what it looks like:
//list of inner classes, if any
Class[] classlist = A.class.getDeclaredClasses();
A outer = new A();
try {
for (int i =0; i < classlist.length; i++){
if (! classlist.getSimpleName().equals("B")){
//skip other classes
continue;
//this is what I mention above.
Constructor constr = classlist[i].getDeclaredConstructor(A.class);
constr.setAccessible(true);
Object inner = constr.newInstance(outer);
Method meth = classlist[i].getDeclaredMethod("testMethod");
meth.setAccessible(true);
//the actual method call
meth.invoke(inner);
} catch (Exception e) {
throw new RuntimeException(e);
Good luck, and if you find yourself relying on this too much, it might mean a code redesign. -
Anything wrong with the code to call method of an external class ??
I have written this code to invoke metod1 in MethodList.java. :
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import com.sun.org.apache.bcel.internal.util.ClassLoader;
public class RunMthdRef
public static void main(String[] args)
URLClassLoader loader = null;
File file = new File("C:\\Documents and Settings\\227951\\workspace\\Methodcaller\\");
String classpath = System.getProperty("java.class.path") + System.getProperty("path.separator") + file.getPath();
System.setProperty("java.class.path",classpath);
try
loader = new URLClassLoader(new URL[]{file.toURL()});
catch (MalformedURLException e)
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread().setContextClassLoader(loader);
try
Class B=loader.loadClass("MethodCaller.MethodList");
Object objectInstance = B.newInstance();
Method startup =B.getMethod("Method1", null);
startup.invoke(objectInstance,null);
catch (Exception e)
e.printStackTrace();
I want to invoke the Method1 in this class present in the same project :
public class MethodList {
// declaring method 1
public void Method1()
Method2();
Method4();
// declaring method 2
public void Method2()
Method3();
// declaring method 2
public void Method3()
System.out.println("End of method list");
// declaring method 4
public void Method4()
Method3();
* @param args
}I have written this code to invoke metod1 in MethodList.java. :Why?
import com.sun.org.apache.bcel.internal.util.ClassLoader;Why?
System.setProperty("java.class.path",classpath);That won't work. It's read-only, and too late to set it anyway.
Class B=loader.loadClass("MethodCaller.MethodList");If 'MethodCaller' is the name of a package you need to study the standard Java coding conventions. Google will find them.
Object objectInstance = B.newInstance();
Method startup =B.getMethod("Method1", null);
startup.invoke(objectInstance,null);Do you really have to do all this reflectively?
I want to invoke the Method1 in this class present in the same project :If it's in the same project why do you need reflection? and dynamic class-loading? -
How do I call an Application Module method from a EntityImpl class?
Guys and Gals,
Using Studio Edition Version 11.1.1.3.0.
I've got a price update form, that when submitted, takes the part numbers and prices in the form and updates the corresponding Parts' price in the Parts table. Anytime this Parts view object's ReplacementPrice attribute is changed, an application module method needs to be called which updates a whole slew of related view objects. I know you can modify view objects via associations (How do I call an Application Module method from a ViewObjectImpl class? but that's not what I'm trying to do. These AppModuleImpl methods are the hub for all price updates, as many different operations may affect related pricing (base price lists, price buckets, etc) and hence, call the updatePartPricing(key) method.
For some reason, the below code does not call / run / activate the application module's method. The AppModuleDataControl exists and recordPartHistory(key) is registered and public. At runtime, the am.<method> code is simply ignored, and as a weird side-effect, I cannot navigate out of my current page flow.
public void setReplacementPrice(Number value)
setAttributeInternal(REPLACEMENTPRICE, value);
AppModuleImpl am = (AppModuleImpl)this.getDBTransaction().findApplicationModule("AppModuleDataControl");
Key key = new Key(new Object[]
{ getPartNumber() });
am.recordPartHistory(key); // AppModuleImpl method which records pricing history
am.updatePartPricing(key); // AppModuleImpl method which updates a whole slew of related pricing tables
}Any ideas?Thanks Timo.
Turns out the code provided was correct, but the AppModuleImpl method being called was not. A dependent ViewObject wasn't returning the row I was expecting. I then tried to perform some operations on that row, which in turn ... just stopped everything, but didn't give me an error.
It was the lack of the error that threw me off. I had never messed with calling an AppModuleImpl method from the EntityImpl so I assumed that's what was messing up.
You are correct. It is available from the ViewRow, but I thought it better to put it in the EntityImpl. This method will be called every time the replacement cost is modified. If I didn't put it in the EntityImpl, I'd have to remember to call it every time a replacement cost changed. -
Using a dynamic variable in the Import command of a Method call
Hi,
I am trying to make a Method call fully dynamic.
I have found out how to make the Method name dynamic, but I am having trouble figuring out how to make the Importing statement dynamic.
in my code below:
CALL METHOD o_main->(v_call)
IMPORTING
it_ekko = i_ekko.
I would like to know if it's possible to make both "it_ekko" AND "i_ekko" dynamic so I can use this same call for various tables.
Hope that makes sense...thanks for your help.
AndyHi Andrew,
The method call is fully dynamic; not only the parameters can be specified dynamically but also the method name.
This is a help extract:
DATA: line TYPE c LENGTH 80,
text_tab LIKE STANDARD TABLE OF line,
filename TYPE string,
filetype TYPE c LENGTH 10,
fleng TYPE i.
DATA: meth TYPE string,
class TYPE string,
ptab TYPE abap_parmbind_tab,
ptab_line TYPE abap_parmbind,
etab TYPE abap_excpbind_tab,
etab_line TYPE abap_excpbind.
DATA: exc_ref TYPE REF TO cx_sy_dyn_call_error,
exc_text TYPE string.
class = 'CL_GUI_FRONTEND_SERVICES'.
meth = 'GUI_DOWNLOAD'.
filename = 'c:\temp\text.txt'.
filetype = 'ASC'.
ptab_line-name = 'FILENAME'.
ptab_line-kind = cl_abap_objectdescr=>exporting.
GET REFERENCE OF filename INTO ptab_line-value.
INSERT ptab_line INTO TABLE ptab.
ptab_line-name = 'FILETYPE'.
ptab_line-kind = cl_abap_objectdescr=>exporting.
GET REFERENCE OF filetype INTO ptab_line-value.
INSERT ptab_line INTO TABLE ptab.
ptab_line-name = 'DATA_TAB'.
ptab_line-kind = cl_abap_objectdescr=>changing.
GET REFERENCE OF text_tab INTO ptab_line-value.
INSERT ptab_line INTO TABLE ptab.
ptab_line-name = 'FILELENGTH'.
ptab_line-kind = cl_abap_objectdescr=>importing.
GET REFERENCE OF fleng INTO ptab_line-value.
INSERT ptab_line INTO TABLE ptab.
etab_line-name = 'OTHERS'.
etab_line-value = 4.
INSERT etab_line INTO TABLE etab.
TRY.
CALL METHOD (class)=>(meth)
PARAMETER-TABLE
ptab
EXCEPTION-TABLE
etab.
CASE sy-subrc.
WHEN 1.
ENDCASE.
CATCH cx_sy_dyn_call_error INTO exc_ref.
exc_text = exc_ref->get_text( ).
MESSAGE exc_text TYPE 'I'.
ENDTRY.
BR,
Valentin
Maybe you are looking for
-
Is the 4th generation time capsule as fast as the 5th generation extreme
is the 4th generation time capsule as fast as the 5th generation airport extreme?
-
Hi there, I hope someone can point me to the right direction here ;-) We have an OSX Lion server 10.7.5. Recently we added a fibercard to it with connection to emc storage. I created in total 6 partitions with each 3 TB on it. For each partition I cr
-
Create web service consumer client with Ant and wsdl
How can I create a web service client with just Ant and WSDL? Thanks.
-
Hi All,, How to create new EO based VO for standard existing oaf page. Can we create EO based VO , manually by writing code in the controller. If yes,,, Could you please help me with code ............ Thanks Kalyan
-
I can't find a program that can play the videos that I record with my iPad. I know it's not my laptop, but I need a program to play the recordings. I have tried windows media player, Apple QuickTime player, VCL Media player Windows media player class