How to link arrays to methods
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
I'm wondering if there is a way to link an array value to a certain method. I have a program with numerous methods, and a method runs when a certain condition exists in a giant if script. I find this slow and inefficient. I was wondering if I could make an array where each value links to the corresponding method to be executed.
For example: if I have a number from 0 - 99, and I want to run a certain method based on whatever number I pick. Instead of making an if script with 100 different cases, could I make an array that has the corresponding method? All of the methods are in one class, and each number has its own method. It would look something like this:
int num = 73;
methods[num](parameters);
I don't know if something like this is even possible. Any help is greatly appreciated!
java arrays syntax
|
show 3 more comments
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
I'm wondering if there is a way to link an array value to a certain method. I have a program with numerous methods, and a method runs when a certain condition exists in a giant if script. I find this slow and inefficient. I was wondering if I could make an array where each value links to the corresponding method to be executed.
For example: if I have a number from 0 - 99, and I want to run a certain method based on whatever number I pick. Instead of making an if script with 100 different cases, could I make an array that has the corresponding method? All of the methods are in one class, and each number has its own method. It would look something like this:
int num = 73;
methods[num](parameters);
I don't know if something like this is even possible. Any help is greatly appreciated!
java arrays syntax
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
2
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an arraytasksof ScriptTask. Then use tasks[num].execute(parameters);
– JB Nizet
Dec 31 '18 at 16:37
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48
|
show 3 more comments
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
I'm wondering if there is a way to link an array value to a certain method. I have a program with numerous methods, and a method runs when a certain condition exists in a giant if script. I find this slow and inefficient. I was wondering if I could make an array where each value links to the corresponding method to be executed.
For example: if I have a number from 0 - 99, and I want to run a certain method based on whatever number I pick. Instead of making an if script with 100 different cases, could I make an array that has the corresponding method? All of the methods are in one class, and each number has its own method. It would look something like this:
int num = 73;
methods[num](parameters);
I don't know if something like this is even possible. Any help is greatly appreciated!
java arrays syntax
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
I'm wondering if there is a way to link an array value to a certain method. I have a program with numerous methods, and a method runs when a certain condition exists in a giant if script. I find this slow and inefficient. I was wondering if I could make an array where each value links to the corresponding method to be executed.
For example: if I have a number from 0 - 99, and I want to run a certain method based on whatever number I pick. Instead of making an if script with 100 different cases, could I make an array that has the corresponding method? All of the methods are in one class, and each number has its own method. It would look something like this:
int num = 73;
methods[num](parameters);
I don't know if something like this is even possible. Any help is greatly appreciated!
java arrays syntax
java arrays syntax
edited Dec 31 '18 at 16:50
Victor Resnov
asked Dec 31 '18 at 16:33
Victor Resnov Victor Resnov
394
394
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
2
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an arraytasksof ScriptTask. Then use tasks[num].execute(parameters);
– JB Nizet
Dec 31 '18 at 16:37
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48
|
show 3 more comments
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
2
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an arraytasksof ScriptTask. Then use tasks[num].execute(parameters);
– JB Nizet
Dec 31 '18 at 16:37
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
2
2
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array
tasks of ScriptTask. Then use tasks[num].execute(parameters);– JB Nizet
Dec 31 '18 at 16:37
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array
tasks of ScriptTask. Then use tasks[num].execute(parameters);– JB Nizet
Dec 31 '18 at 16:37
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48
|
show 3 more comments
7 Answers
7
active
oldest
votes
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array tasks of ScriptTask. Then use tasks[num].execute(parameters).
Example:
@FunctionalInterface
interface ScriptTask {
void execute(String s, int i);
}
class Script {
private ScriptTask tasks;
Script() {
this.tasks = new ScriptTask[2];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
}
private void foo(String s, int i) {
System.out.println(s);
}
private void bar(String s, int i) {
System.out.println(i);
}
void run() {
for (int i = 0; i < tasks.length; i++) {
tasks[i].execute("hello", i);
}
}
public static void main(String args) {
new Script().run();
}
}
Note that if you really have 100 different methods in a single class, that's a clear sign that it should be refactored into several different simpler classes, that can be read, understood and tested more easily. The above is the first step for the refactoring: you can refactor each method into a separate class implementing the ScriptTask interface.
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
add a comment |
You need to pass the Object of the class in which method is defined, get method name from array and pass arguments. Posting only the required code.
public static Object invokeExactMethod(Object object, String methodName, Object... args) {
if (null == args) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?> parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
invokeExactMethod() is method provided my MethodUtils class of apache commons.
Hope this helps..!!
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think myMethodapproach gets closer to what OP wanted.
– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however callinginvokeExactMethod(MyClass,"methodName",args)is not what OP was expecting, super useful anyway.
– LeedMx
Dec 31 '18 at 20:14
add a comment |
Can create an interface for saving the methods to run, for example :
public interface MethodRunner {
public void run();
}
Define the array and add an instance of MethodRunner.
MethodRunner methodsRunners = new MethodRunner[n];
methodsRunners[0] = new MethodRunner() {
@Override
public void run() {
// some method here
}
};
methodsRunners[0] = ...
.
.
methodsRunners[n] = ...
And run it by following way :
methodsRunners[n].run();
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
add a comment |
Well, I think we can make use of Reflection in order to achieve this as follows"
1.) Class to store info about the methods
public class MethodInfo {
public String methodName;
public Class<?> params;
}
2.) Class consisting of all the methods
public class Task {
public void method1(int x, ......){
}
And So On..
}
3.) Main class creating array and using it. Here using Reflection we can access methods from array and invoke them.
public class MainClass {
public static void main(String args) {
MethodInfo firstMethod = new MethodInfo();
firstMethod.methodName = "method1";
firstMethod.params = Array OF Parameter Types(.class values)
MethodInfo methods = new MethodInfo[10];
methods[1] = firstMethod;
java.lang.reflect.Method method = Task.class.getMethod(methods[1].methodName, methods[1].params);
method.invoke(new Task(), param1, param2,....);
}
}
add a comment |
in addition to the answer of JB Nizet, other variants of syntax can be used:
this.tasks = new ScriptTask[4];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
this.tasks[2] = (String s, int i) -> {
System.out.println(s);
};
this.tasks[3] = (String s, int i) -> System.out.println(s);
or even:
this.tasks = new ScriptTask {
this::foo,
this::bar,
(String s, int i) -> {
System.out.println(s);
},
(String s, int i) -> System.out.println(s)
};
add a comment |
In the program I am working on I accomplished this by creating constructors with overwritten methods.
public class Script
{
public Script()
{
}
public void run()
{
}
}
public class TestScript extends Script
{
public TestScript()
{
}
public void run()
{
//This Method overwrites the run method of script. This is where your code goes.
}
}
public class Main
{
public static Script test = new TestScript();
public static void main(String args)
{
test.run();
}
}
Yes they can, you can achieve it using a@FunctionalInterfaceas @JB answered
– ngueno
Dec 31 '18 at 16:51
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
add a comment |
I'm wondering if there is a way to link an array value to a certain method.
You can use reflection to generate an Array of methods. However, this is a "not ideal solution" because it will make your code hard to maintain. So, I have to say this is not good practice but here it is.
package methodarray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodArray {
public static void main(String args) {
Method arrayOfMethods = new Method[100];
try {
//...You will need to add the methods by their name, you can use for loops to add them quickly
arrayOfMethods[1] = MethodArray.class.getDeclaredMethod("someMethodName");
arrayOfMethods[2] = MethodArray.class.getDeclaredMethod("someOtherMethod");
//...
} catch (NoSuchMethodException | SecurityException ex) {
//this can throw an Exception if the method is not found, handle it here
}
//now to call a method from the array just do
try {
arrayOfMethods[1].invoke(MethodArray.class);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//...handle exceptions
}
}
public void someMethodName(){
//...logic
}
public void someOtherMethod(){
//...logic
}
}
This would help you call the methods just like you want, but keep in mind that for security java might throw several expections when using reflection. To send additional arguments just call arrayOfMethods[n].invoke(MethodArray.class, args);
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
For solving these types of common scenarios we use Design Patterns, patterns are tested solutions for common scenarios. All the answers saying that you should "use an interface" are actually trying to help you achieve that, the pattern you might be able to use is called Command Pattern you can read about it here. Understanding or reading about the pattern might not be useful since you've said that you are not familiar with using interfaces. (Personally I always recommend Head First Design Patterns as an introductory book to patterns.)
Once you understand the command pattern you can simply generate an array of commands, this is a better OO solution, keep that in mind. I won't make an example since I think is hard to understand if you don't have a clear idea on how to use interfaces, read about them, it will be worth it!!!
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53989521%2fhow-to-link-arrays-to-methods%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array tasks of ScriptTask. Then use tasks[num].execute(parameters).
Example:
@FunctionalInterface
interface ScriptTask {
void execute(String s, int i);
}
class Script {
private ScriptTask tasks;
Script() {
this.tasks = new ScriptTask[2];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
}
private void foo(String s, int i) {
System.out.println(s);
}
private void bar(String s, int i) {
System.out.println(i);
}
void run() {
for (int i = 0; i < tasks.length; i++) {
tasks[i].execute("hello", i);
}
}
public static void main(String args) {
new Script().run();
}
}
Note that if you really have 100 different methods in a single class, that's a clear sign that it should be refactored into several different simpler classes, that can be read, understood and tested more easily. The above is the first step for the refactoring: you can refactor each method into a separate class implementing the ScriptTask interface.
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
add a comment |
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array tasks of ScriptTask. Then use tasks[num].execute(parameters).
Example:
@FunctionalInterface
interface ScriptTask {
void execute(String s, int i);
}
class Script {
private ScriptTask tasks;
Script() {
this.tasks = new ScriptTask[2];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
}
private void foo(String s, int i) {
System.out.println(s);
}
private void bar(String s, int i) {
System.out.println(i);
}
void run() {
for (int i = 0; i < tasks.length; i++) {
tasks[i].execute("hello", i);
}
}
public static void main(String args) {
new Script().run();
}
}
Note that if you really have 100 different methods in a single class, that's a clear sign that it should be refactored into several different simpler classes, that can be read, understood and tested more easily. The above is the first step for the refactoring: you can refactor each method into a separate class implementing the ScriptTask interface.
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
add a comment |
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array tasks of ScriptTask. Then use tasks[num].execute(parameters).
Example:
@FunctionalInterface
interface ScriptTask {
void execute(String s, int i);
}
class Script {
private ScriptTask tasks;
Script() {
this.tasks = new ScriptTask[2];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
}
private void foo(String s, int i) {
System.out.println(s);
}
private void bar(String s, int i) {
System.out.println(i);
}
void run() {
for (int i = 0; i < tasks.length; i++) {
tasks[i].execute("hello", i);
}
}
public static void main(String args) {
new Script().run();
}
}
Note that if you really have 100 different methods in a single class, that's a clear sign that it should be refactored into several different simpler classes, that can be read, understood and tested more easily. The above is the first step for the refactoring: you can refactor each method into a separate class implementing the ScriptTask interface.
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array tasks of ScriptTask. Then use tasks[num].execute(parameters).
Example:
@FunctionalInterface
interface ScriptTask {
void execute(String s, int i);
}
class Script {
private ScriptTask tasks;
Script() {
this.tasks = new ScriptTask[2];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
}
private void foo(String s, int i) {
System.out.println(s);
}
private void bar(String s, int i) {
System.out.println(i);
}
void run() {
for (int i = 0; i < tasks.length; i++) {
tasks[i].execute("hello", i);
}
}
public static void main(String args) {
new Script().run();
}
}
Note that if you really have 100 different methods in a single class, that's a clear sign that it should be refactored into several different simpler classes, that can be read, understood and tested more easily. The above is the first step for the refactoring: you can refactor each method into a separate class implementing the ScriptTask interface.
edited Dec 31 '18 at 16:55
answered Dec 31 '18 at 16:49
JB NizetJB Nizet
540k568741004
540k568741004
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
add a comment |
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
Okay. Thanks for your help!
– Victor Resnov
Dec 31 '18 at 17:03
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
This is the command pattern again!...
– LeedMx
Dec 31 '18 at 17:57
add a comment |
You need to pass the Object of the class in which method is defined, get method name from array and pass arguments. Posting only the required code.
public static Object invokeExactMethod(Object object, String methodName, Object... args) {
if (null == args) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?> parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
invokeExactMethod() is method provided my MethodUtils class of apache commons.
Hope this helps..!!
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think myMethodapproach gets closer to what OP wanted.
– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however callinginvokeExactMethod(MyClass,"methodName",args)is not what OP was expecting, super useful anyway.
– LeedMx
Dec 31 '18 at 20:14
add a comment |
You need to pass the Object of the class in which method is defined, get method name from array and pass arguments. Posting only the required code.
public static Object invokeExactMethod(Object object, String methodName, Object... args) {
if (null == args) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?> parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
invokeExactMethod() is method provided my MethodUtils class of apache commons.
Hope this helps..!!
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think myMethodapproach gets closer to what OP wanted.
– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however callinginvokeExactMethod(MyClass,"methodName",args)is not what OP was expecting, super useful anyway.
– LeedMx
Dec 31 '18 at 20:14
add a comment |
You need to pass the Object of the class in which method is defined, get method name from array and pass arguments. Posting only the required code.
public static Object invokeExactMethod(Object object, String methodName, Object... args) {
if (null == args) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?> parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
invokeExactMethod() is method provided my MethodUtils class of apache commons.
Hope this helps..!!
You need to pass the Object of the class in which method is defined, get method name from array and pass arguments. Posting only the required code.
public static Object invokeExactMethod(Object object, String methodName, Object... args) {
if (null == args) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?> parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
invokeExactMethod() is method provided my MethodUtils class of apache commons.
Hope this helps..!!
answered Dec 31 '18 at 17:53
Nihal KothariNihal Kothari
112
112
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think myMethodapproach gets closer to what OP wanted.
– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however callinginvokeExactMethod(MyClass,"methodName",args)is not what OP was expecting, super useful anyway.
– LeedMx
Dec 31 '18 at 20:14
add a comment |
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think myMethodapproach gets closer to what OP wanted.
– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however callinginvokeExactMethod(MyClass,"methodName",args)is not what OP was expecting, super useful anyway.
– LeedMx
Dec 31 '18 at 20:14
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
This is a good use of reflection, but if we are trying to achieve an array of methods why wouldn't you just do an array of methods?
– LeedMx
Dec 31 '18 at 17:59
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
We can store all the method names in an array and whichever method needs to be invoked, we just need to get that method name from array and pass to this method along with class and parameters.
– Nihal Kothari
Dec 31 '18 at 18:05
Storing methods' names in a String is an excellent idea; But I think my
Method approach gets closer to what OP wanted.– LeedMx
Dec 31 '18 at 18:13
Storing methods' names in a String is an excellent idea; But I think my
Method approach gets closer to what OP wanted.– LeedMx
Dec 31 '18 at 18:13
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Yeah what you said may be right but given requirement can be achieved in this way as well. Based on the case ex: 73 which can be used as index in the array to get corresponding method name from array.
– Nihal Kothari
Dec 31 '18 at 20:07
Voted as helpful, its a clever and decoupled solution, however calling
invokeExactMethod(MyClass,"methodName",args) is not what OP was expecting, super useful anyway.– LeedMx
Dec 31 '18 at 20:14
Voted as helpful, its a clever and decoupled solution, however calling
invokeExactMethod(MyClass,"methodName",args) is not what OP was expecting, super useful anyway.– LeedMx
Dec 31 '18 at 20:14
add a comment |
Can create an interface for saving the methods to run, for example :
public interface MethodRunner {
public void run();
}
Define the array and add an instance of MethodRunner.
MethodRunner methodsRunners = new MethodRunner[n];
methodsRunners[0] = new MethodRunner() {
@Override
public void run() {
// some method here
}
};
methodsRunners[0] = ...
.
.
methodsRunners[n] = ...
And run it by following way :
methodsRunners[n].run();
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
add a comment |
Can create an interface for saving the methods to run, for example :
public interface MethodRunner {
public void run();
}
Define the array and add an instance of MethodRunner.
MethodRunner methodsRunners = new MethodRunner[n];
methodsRunners[0] = new MethodRunner() {
@Override
public void run() {
// some method here
}
};
methodsRunners[0] = ...
.
.
methodsRunners[n] = ...
And run it by following way :
methodsRunners[n].run();
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
add a comment |
Can create an interface for saving the methods to run, for example :
public interface MethodRunner {
public void run();
}
Define the array and add an instance of MethodRunner.
MethodRunner methodsRunners = new MethodRunner[n];
methodsRunners[0] = new MethodRunner() {
@Override
public void run() {
// some method here
}
};
methodsRunners[0] = ...
.
.
methodsRunners[n] = ...
And run it by following way :
methodsRunners[n].run();
Can create an interface for saving the methods to run, for example :
public interface MethodRunner {
public void run();
}
Define the array and add an instance of MethodRunner.
MethodRunner methodsRunners = new MethodRunner[n];
methodsRunners[0] = new MethodRunner() {
@Override
public void run() {
// some method here
}
};
methodsRunners[0] = ...
.
.
methodsRunners[n] = ...
And run it by following way :
methodsRunners[n].run();
answered Dec 31 '18 at 16:54
Jonathan JohxJonathan Johx
1,7761317
1,7761317
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
add a comment |
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
This is exactly Command pattern, we developer need to get up to speed in the lingo we use
– LeedMx
Dec 31 '18 at 17:55
add a comment |
Well, I think we can make use of Reflection in order to achieve this as follows"
1.) Class to store info about the methods
public class MethodInfo {
public String methodName;
public Class<?> params;
}
2.) Class consisting of all the methods
public class Task {
public void method1(int x, ......){
}
And So On..
}
3.) Main class creating array and using it. Here using Reflection we can access methods from array and invoke them.
public class MainClass {
public static void main(String args) {
MethodInfo firstMethod = new MethodInfo();
firstMethod.methodName = "method1";
firstMethod.params = Array OF Parameter Types(.class values)
MethodInfo methods = new MethodInfo[10];
methods[1] = firstMethod;
java.lang.reflect.Method method = Task.class.getMethod(methods[1].methodName, methods[1].params);
method.invoke(new Task(), param1, param2,....);
}
}
add a comment |
Well, I think we can make use of Reflection in order to achieve this as follows"
1.) Class to store info about the methods
public class MethodInfo {
public String methodName;
public Class<?> params;
}
2.) Class consisting of all the methods
public class Task {
public void method1(int x, ......){
}
And So On..
}
3.) Main class creating array and using it. Here using Reflection we can access methods from array and invoke them.
public class MainClass {
public static void main(String args) {
MethodInfo firstMethod = new MethodInfo();
firstMethod.methodName = "method1";
firstMethod.params = Array OF Parameter Types(.class values)
MethodInfo methods = new MethodInfo[10];
methods[1] = firstMethod;
java.lang.reflect.Method method = Task.class.getMethod(methods[1].methodName, methods[1].params);
method.invoke(new Task(), param1, param2,....);
}
}
add a comment |
Well, I think we can make use of Reflection in order to achieve this as follows"
1.) Class to store info about the methods
public class MethodInfo {
public String methodName;
public Class<?> params;
}
2.) Class consisting of all the methods
public class Task {
public void method1(int x, ......){
}
And So On..
}
3.) Main class creating array and using it. Here using Reflection we can access methods from array and invoke them.
public class MainClass {
public static void main(String args) {
MethodInfo firstMethod = new MethodInfo();
firstMethod.methodName = "method1";
firstMethod.params = Array OF Parameter Types(.class values)
MethodInfo methods = new MethodInfo[10];
methods[1] = firstMethod;
java.lang.reflect.Method method = Task.class.getMethod(methods[1].methodName, methods[1].params);
method.invoke(new Task(), param1, param2,....);
}
}
Well, I think we can make use of Reflection in order to achieve this as follows"
1.) Class to store info about the methods
public class MethodInfo {
public String methodName;
public Class<?> params;
}
2.) Class consisting of all the methods
public class Task {
public void method1(int x, ......){
}
And So On..
}
3.) Main class creating array and using it. Here using Reflection we can access methods from array and invoke them.
public class MainClass {
public static void main(String args) {
MethodInfo firstMethod = new MethodInfo();
firstMethod.methodName = "method1";
firstMethod.params = Array OF Parameter Types(.class values)
MethodInfo methods = new MethodInfo[10];
methods[1] = firstMethod;
java.lang.reflect.Method method = Task.class.getMethod(methods[1].methodName, methods[1].params);
method.invoke(new Task(), param1, param2,....);
}
}
answered Dec 31 '18 at 17:05
AnkurAnkur
32418
32418
add a comment |
add a comment |
in addition to the answer of JB Nizet, other variants of syntax can be used:
this.tasks = new ScriptTask[4];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
this.tasks[2] = (String s, int i) -> {
System.out.println(s);
};
this.tasks[3] = (String s, int i) -> System.out.println(s);
or even:
this.tasks = new ScriptTask {
this::foo,
this::bar,
(String s, int i) -> {
System.out.println(s);
},
(String s, int i) -> System.out.println(s)
};
add a comment |
in addition to the answer of JB Nizet, other variants of syntax can be used:
this.tasks = new ScriptTask[4];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
this.tasks[2] = (String s, int i) -> {
System.out.println(s);
};
this.tasks[3] = (String s, int i) -> System.out.println(s);
or even:
this.tasks = new ScriptTask {
this::foo,
this::bar,
(String s, int i) -> {
System.out.println(s);
},
(String s, int i) -> System.out.println(s)
};
add a comment |
in addition to the answer of JB Nizet, other variants of syntax can be used:
this.tasks = new ScriptTask[4];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
this.tasks[2] = (String s, int i) -> {
System.out.println(s);
};
this.tasks[3] = (String s, int i) -> System.out.println(s);
or even:
this.tasks = new ScriptTask {
this::foo,
this::bar,
(String s, int i) -> {
System.out.println(s);
},
(String s, int i) -> System.out.println(s)
};
in addition to the answer of JB Nizet, other variants of syntax can be used:
this.tasks = new ScriptTask[4];
this.tasks[0] = this::foo;
this.tasks[1] = this::bar;
this.tasks[2] = (String s, int i) -> {
System.out.println(s);
};
this.tasks[3] = (String s, int i) -> System.out.println(s);
or even:
this.tasks = new ScriptTask {
this::foo,
this::bar,
(String s, int i) -> {
System.out.println(s);
},
(String s, int i) -> System.out.println(s)
};
answered Dec 31 '18 at 17:12
Alexei KaigorodovAlexei Kaigorodov
10.1k11029
10.1k11029
add a comment |
add a comment |
In the program I am working on I accomplished this by creating constructors with overwritten methods.
public class Script
{
public Script()
{
}
public void run()
{
}
}
public class TestScript extends Script
{
public TestScript()
{
}
public void run()
{
//This Method overwrites the run method of script. This is where your code goes.
}
}
public class Main
{
public static Script test = new TestScript();
public static void main(String args)
{
test.run();
}
}
Yes they can, you can achieve it using a@FunctionalInterfaceas @JB answered
– ngueno
Dec 31 '18 at 16:51
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
add a comment |
In the program I am working on I accomplished this by creating constructors with overwritten methods.
public class Script
{
public Script()
{
}
public void run()
{
}
}
public class TestScript extends Script
{
public TestScript()
{
}
public void run()
{
//This Method overwrites the run method of script. This is where your code goes.
}
}
public class Main
{
public static Script test = new TestScript();
public static void main(String args)
{
test.run();
}
}
Yes they can, you can achieve it using a@FunctionalInterfaceas @JB answered
– ngueno
Dec 31 '18 at 16:51
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
add a comment |
In the program I am working on I accomplished this by creating constructors with overwritten methods.
public class Script
{
public Script()
{
}
public void run()
{
}
}
public class TestScript extends Script
{
public TestScript()
{
}
public void run()
{
//This Method overwrites the run method of script. This is where your code goes.
}
}
public class Main
{
public static Script test = new TestScript();
public static void main(String args)
{
test.run();
}
}
In the program I am working on I accomplished this by creating constructors with overwritten methods.
public class Script
{
public Script()
{
}
public void run()
{
}
}
public class TestScript extends Script
{
public TestScript()
{
}
public void run()
{
//This Method overwrites the run method of script. This is where your code goes.
}
}
public class Main
{
public static Script test = new TestScript();
public static void main(String args)
{
test.run();
}
}
edited Dec 31 '18 at 17:14
answered Dec 31 '18 at 16:48
JakeJake
11
11
Yes they can, you can achieve it using a@FunctionalInterfaceas @JB answered
– ngueno
Dec 31 '18 at 16:51
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
add a comment |
Yes they can, you can achieve it using a@FunctionalInterfaceas @JB answered
– ngueno
Dec 31 '18 at 16:51
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
Yes they can, you can achieve it using a
@FunctionalInterface as @JB answered– ngueno
Dec 31 '18 at 16:51
Yes they can, you can achieve it using a
@FunctionalInterface as @JB answered– ngueno
Dec 31 '18 at 16:51
1
1
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
I did not know this as I searched for such a solution quite awhile ago, pretty neat. I might be able to make use of this.
– Jake
Dec 31 '18 at 16:56
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
@ngueno Conceptually, a functional interface has exactly one abstract method. Please don't confuse him because the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. According documentation docs.oracle.com/javase/8/docs/api/java/lang/…
– Jonathan Johx
Dec 31 '18 at 17:02
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Then an answer is simply use an interface as via to run/execute some method in order to abstract it like hierarchy
– Jonathan Johx
Dec 31 '18 at 17:05
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
Once again, this is the Command pattern in action.
– LeedMx
Dec 31 '18 at 17:57
add a comment |
I'm wondering if there is a way to link an array value to a certain method.
You can use reflection to generate an Array of methods. However, this is a "not ideal solution" because it will make your code hard to maintain. So, I have to say this is not good practice but here it is.
package methodarray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodArray {
public static void main(String args) {
Method arrayOfMethods = new Method[100];
try {
//...You will need to add the methods by their name, you can use for loops to add them quickly
arrayOfMethods[1] = MethodArray.class.getDeclaredMethod("someMethodName");
arrayOfMethods[2] = MethodArray.class.getDeclaredMethod("someOtherMethod");
//...
} catch (NoSuchMethodException | SecurityException ex) {
//this can throw an Exception if the method is not found, handle it here
}
//now to call a method from the array just do
try {
arrayOfMethods[1].invoke(MethodArray.class);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//...handle exceptions
}
}
public void someMethodName(){
//...logic
}
public void someOtherMethod(){
//...logic
}
}
This would help you call the methods just like you want, but keep in mind that for security java might throw several expections when using reflection. To send additional arguments just call arrayOfMethods[n].invoke(MethodArray.class, args);
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
For solving these types of common scenarios we use Design Patterns, patterns are tested solutions for common scenarios. All the answers saying that you should "use an interface" are actually trying to help you achieve that, the pattern you might be able to use is called Command Pattern you can read about it here. Understanding or reading about the pattern might not be useful since you've said that you are not familiar with using interfaces. (Personally I always recommend Head First Design Patterns as an introductory book to patterns.)
Once you understand the command pattern you can simply generate an array of commands, this is a better OO solution, keep that in mind. I won't make an example since I think is hard to understand if you don't have a clear idea on how to use interfaces, read about them, it will be worth it!!!
add a comment |
I'm wondering if there is a way to link an array value to a certain method.
You can use reflection to generate an Array of methods. However, this is a "not ideal solution" because it will make your code hard to maintain. So, I have to say this is not good practice but here it is.
package methodarray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodArray {
public static void main(String args) {
Method arrayOfMethods = new Method[100];
try {
//...You will need to add the methods by their name, you can use for loops to add them quickly
arrayOfMethods[1] = MethodArray.class.getDeclaredMethod("someMethodName");
arrayOfMethods[2] = MethodArray.class.getDeclaredMethod("someOtherMethod");
//...
} catch (NoSuchMethodException | SecurityException ex) {
//this can throw an Exception if the method is not found, handle it here
}
//now to call a method from the array just do
try {
arrayOfMethods[1].invoke(MethodArray.class);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//...handle exceptions
}
}
public void someMethodName(){
//...logic
}
public void someOtherMethod(){
//...logic
}
}
This would help you call the methods just like you want, but keep in mind that for security java might throw several expections when using reflection. To send additional arguments just call arrayOfMethods[n].invoke(MethodArray.class, args);
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
For solving these types of common scenarios we use Design Patterns, patterns are tested solutions for common scenarios. All the answers saying that you should "use an interface" are actually trying to help you achieve that, the pattern you might be able to use is called Command Pattern you can read about it here. Understanding or reading about the pattern might not be useful since you've said that you are not familiar with using interfaces. (Personally I always recommend Head First Design Patterns as an introductory book to patterns.)
Once you understand the command pattern you can simply generate an array of commands, this is a better OO solution, keep that in mind. I won't make an example since I think is hard to understand if you don't have a clear idea on how to use interfaces, read about them, it will be worth it!!!
add a comment |
I'm wondering if there is a way to link an array value to a certain method.
You can use reflection to generate an Array of methods. However, this is a "not ideal solution" because it will make your code hard to maintain. So, I have to say this is not good practice but here it is.
package methodarray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodArray {
public static void main(String args) {
Method arrayOfMethods = new Method[100];
try {
//...You will need to add the methods by their name, you can use for loops to add them quickly
arrayOfMethods[1] = MethodArray.class.getDeclaredMethod("someMethodName");
arrayOfMethods[2] = MethodArray.class.getDeclaredMethod("someOtherMethod");
//...
} catch (NoSuchMethodException | SecurityException ex) {
//this can throw an Exception if the method is not found, handle it here
}
//now to call a method from the array just do
try {
arrayOfMethods[1].invoke(MethodArray.class);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//...handle exceptions
}
}
public void someMethodName(){
//...logic
}
public void someOtherMethod(){
//...logic
}
}
This would help you call the methods just like you want, but keep in mind that for security java might throw several expections when using reflection. To send additional arguments just call arrayOfMethods[n].invoke(MethodArray.class, args);
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
For solving these types of common scenarios we use Design Patterns, patterns are tested solutions for common scenarios. All the answers saying that you should "use an interface" are actually trying to help you achieve that, the pattern you might be able to use is called Command Pattern you can read about it here. Understanding or reading about the pattern might not be useful since you've said that you are not familiar with using interfaces. (Personally I always recommend Head First Design Patterns as an introductory book to patterns.)
Once you understand the command pattern you can simply generate an array of commands, this is a better OO solution, keep that in mind. I won't make an example since I think is hard to understand if you don't have a clear idea on how to use interfaces, read about them, it will be worth it!!!
I'm wondering if there is a way to link an array value to a certain method.
You can use reflection to generate an Array of methods. However, this is a "not ideal solution" because it will make your code hard to maintain. So, I have to say this is not good practice but here it is.
package methodarray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodArray {
public static void main(String args) {
Method arrayOfMethods = new Method[100];
try {
//...You will need to add the methods by their name, you can use for loops to add them quickly
arrayOfMethods[1] = MethodArray.class.getDeclaredMethod("someMethodName");
arrayOfMethods[2] = MethodArray.class.getDeclaredMethod("someOtherMethod");
//...
} catch (NoSuchMethodException | SecurityException ex) {
//this can throw an Exception if the method is not found, handle it here
}
//now to call a method from the array just do
try {
arrayOfMethods[1].invoke(MethodArray.class);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
//...handle exceptions
}
}
public void someMethodName(){
//...logic
}
public void someOtherMethod(){
//...logic
}
}
This would help you call the methods just like you want, but keep in mind that for security java might throw several expections when using reflection. To send additional arguments just call arrayOfMethods[n].invoke(MethodArray.class, args);
This question is mainly for Java, but if it works for all Object Oriented Programming Languages, then that's good.
For solving these types of common scenarios we use Design Patterns, patterns are tested solutions for common scenarios. All the answers saying that you should "use an interface" are actually trying to help you achieve that, the pattern you might be able to use is called Command Pattern you can read about it here. Understanding or reading about the pattern might not be useful since you've said that you are not familiar with using interfaces. (Personally I always recommend Head First Design Patterns as an introductory book to patterns.)
Once you understand the command pattern you can simply generate an array of commands, this is a better OO solution, keep that in mind. I won't make an example since I think is hard to understand if you don't have a clear idea on how to use interfaces, read about them, it will be worth it!!!
edited Dec 31 '18 at 18:11
answered Dec 31 '18 at 17:50
LeedMxLeedMx
17011
17011
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53989521%2fhow-to-link-arrays-to-methods%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Do you have one method for each number or a range of number (like run method1 for all numbers from 10 to 20)
– user7
Dec 31 '18 at 16:36
2
Define an interface (let's name it ScriptTask) defining the method to execute (let's call it execute). Create an array
tasksof ScriptTask. Then use tasks[num].execute(parameters);– JB Nizet
Dec 31 '18 at 16:37
Each number has its own method.
– Victor Resnov
Dec 31 '18 at 16:38
Each number has its own method, but do all the methods are related to one class in specific?
– ngueno
Dec 31 '18 at 16:46
How would I declare the method and the array? I'm not used to using interfaces. I know what they are, but I'm not sure how to declare them correctly.
– Victor Resnov
Dec 31 '18 at 16:48