简体   繁体   English

如何在Android中将方法作为参数传递

[英]How to pass methods as parameters in Android

This may be a really stupid question or not even possible. 这可能是一个非常愚蠢的问题,甚至是不可能的。

I am not sure if this would be called as a method, but going with this. 我不确定是否可以将其作为方法调用,但是请继续进行下去。 How can I pass getCountryName(); 如何传递getCountryName(); as parameter? 作为参数? like show below; 如下所示;

public static String Utils(Something something){
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    List<Address> address = null;

    if (geoCoder != null) {
        try {
            address = geoCoder.getFromLocation(lat, lng, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (address.size() > 0) {
            return address.get(0).getCountryName(); // pass this as parameter (something)
        }
    }
    return null;
}

and then call it like so, 然后这样称呼它,

Utils(getCountryName());
Utils(getCountryCode());
etc.

This Answer helped me to do it. 这个答案帮助我做到了。 You can try it, too. 您也可以尝试。

Methods aren't first-class objects in Java, so they can't be passed as parameters. 方法不是Java中的一流对象,因此它们不能作为参数传递。 You could use wrap your method call in an annoymous class that extends eg the Runnable interface. 您可以在扩展了Runnable接口的匿名类中使用方法调用包装。

You can use reflection. 您可以使用反射。

eg 例如

Method[] methods = Address.class.getMethods();
for (Method method : methods){
    if(method.getName().equals(param)){
        return (String) method.invoke(address.get(0));
    }
}

param would be of type String with value of the method you want to call. param的类型为String具有您要调用的方法的值。

EDIT: Full example, using getMethod(String) 编辑:使用getMethod(String)完整示例

public static String Utils(String param){
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    List<Address> address = null;

    if (geoCoder != null) {
        try { 
            address = geoCoder.getFromLocation(lat, lng, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
        } 
        if (address.size() > 0) {
            Method method = Address.class.getMethod(param);
            if(method == null) return null;
            try{
                return (String) method.invoke(address.get(0));
            }catch(ReflectiveOperationException e){
                // Expected param maybe?
                return null;
            }
        } 
    } 
    return null; 
} 

In java that is the language that you are finally using. 在Java中,这是您最终使用的语言。 You can't pass a method or function as a parameter to a function. 您不能将方法或函数作为参数传递给函数。 If you are able to use it, from Java 8 you have lambda expressions that are a kind of "anonymous" function. 如果能够使用它,则从Java 8开始,您将拥有lambda表达式,该表达式是一种“匿名”函数。 Try with that. 试试吧。

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

In this SO answer you have a very detailed guide. 在这个答案中,您有一个非常详细的指南。 Java Pass Method as Parameter Java Pass方法作为参数

In that thread there are more info with some patterns if you can't use java8 如果您不能使用java8,那么在该线程中会有更多信息以及某些模式

try this; 尝试这个;

First define an Interface with the method you want to pass as a parameter 首先使用要作为参数传递的方法定义一个接口

public interface Callable {
  public void getCountryName();
  public void getCountryCode();
}

Implement a class with the method 用方法实现一个类

class Method_passing implements Callable {
  public void getCountryName() {
     //do your task
  }

  public void getCountryCode() {
     //do your task
  }
}

Invoke like that 这样调用

Callable cmd = new Method_passing();
//This allows you to pass cmd as parameter and invoke the method call defined in the interface

public invoke( Callable callable ) {
  cmd.getCountryName(); //return name etc..
  cmd.getCountryCode();
}

You could implement a getUtil function inside your adress class and then use identifiers to execute a function of your choice. 您可以在adress类中实现getUtil函数,然后使用标识符执行您选择的函数。

public class Address {
public static final int GET_COUNTRY_NAME = 1;
public static final int GET_COUNTRY_CODE = 2;

public String getUtil(int code){
    switch(code){
    case GET_COUNTRY_NAME: return this.getCountryName();
    case GET_COUNTRY_CODE: return this.getCountryCode();
    default: return null;
    }
}

private String getCountryName(){
    //do something
    return "";
}

private String getCountryCode(){
    //do something
    return "";
}}

and then define your function like 然后定义你的功能像

public static String Utils(int something){
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> address = null;

if (geoCoder != null) {
    try {
        address = geoCoder.getFromLocation(lat, lng, 1);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    if (address.size() > 0) {
        return address.get(0).getUtil(something);
    }
}
return null; }}

which would be called using 这将被称为

Utils(Address.GET_COUNTRY_NAME);
Utils(Address.GET_COUNTRY_CODE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM