public class ArrayOfMethods { public static void main(String[] args) { MethodContainer[] m = new MethodContainer[] { new A(), new B() }; m[0].doSomething(); m[1].doSomething(); } }
interface MethodContainer { public void doSomething(); }
class A implements MethodContainer { public void doSomething() { System.out.println("I am an A"); } }
class B implements MethodContainer { public void doSomething() { System.out.println("I am a B"); } }
hvis den skulle operationaliseres tror jeg at den skulle laves som Map:
import java.lang.reflect.*; import java.util.*;
public class ArrayOfMethodsReflection { public static void main(String[] args)throws Exception { Map<String, Method> m = new HashMap<String, Method>(); for (Method met : ArrayOfMethodsReflection.class.getMethods()) { m.put(met.getName(), met); } m.get("a").invoke(null, new Object[] { }); m.get("b").invoke(null, new Object[] { }); } public static void a() { System.out.println("I am a"); } public static void b() { System.out.println("I am b"); }
jo - det var ikke et effektivitets spørgsmpl men et læsbarheds spørgsmål
import java.lang.reflect.*; import java.util.*;
public class ArrayOfMethodsReflection2 { public static void main(String[] args)throws Exception { List<Method> lst = new ArrayList<Method>(); for (Method met : ArrayOfMethodsReflection2.class.getMethods()) { lst.add(met); } lst.get(2).invoke(null, new Object[] { }); lst.get(1).invoke(null, new Object[] { }); } public static void a() { System.out.println("I am a"); } public static void b() { System.out.println("I am b"); } }
is not obious that it will call a first and b last
og jeg ved faktisk heller ikke om for each iteratoren er lineær
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.