java - Android 在没有 new mClass() 的情况下将类创建到单独的文件中...?

标签 java android class methods

我试图以一种简单的方式处理类,但我无法实现它......

到目前为止...我创建了一个separateClass.java,及其构造函数和方法,但在Main.java中,我以这种方式调用separateClass.java的方法...

// Current way...
separateClass sp = new separateClass(myPathString);
String newPath = sp.myMethod();

// The way I would like...
String newPath = myMethod(myPathString);

// ADDED AFTER RESPONSE...
// This way helps me when I have more classes (.javas)
String newThig = separateClass.myMethod(myPathString);
String anotherThing = myOtherLibrary.methodForSomeThing(someString);
String numCheck = myCalculations.terrain(altitude, latitude);

// Note: The static way is just recomended with simples processes that don't
// need many objects or constructors.
// so far this is what I understand.

这可能吗?我该怎么做? 我很欣赏一些想法! :)

已编辑...

public class separateClass{

    /* Not needed if static (for novices)
    String myPathString;

    public Imagen_DirectorioGestor(String myPathString) {
        this.myPathString= myPathString;
    }
    */

    public static String myMethod(String myPathString){
        File file = new File(myPathString);
        newPath = ...;
        return newPath;
    }

}

最佳答案

将SeparateClass内部的方法设为静态:

public static String myMethod(String path) {
    ...
}

然后从您的 Activity 中调用 myMethod,如下所示:

SeparateClass.myMethod(myPathString);

如果这还不够,您可以在 MainActivity 中导入该方法:

import static com.mypackage.SeparateClass.myMethod;

然后您就可以在没有任何类引用的情况下使用该方法:

myMethod();

关于java - Android 在没有 new mClass() 的情况下将类创建到单独的文件中...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25473569/

相关文章:

android - 即使在提供 "app:layout_scrollFlags"标志后,工具栏也不会滚动

java - 如何在延迟后更新 ImageView(图像)而不卡住 UI 并允许用户点击?

c++ - 在C++中访问类字段

python - 如何使用函数的参数作为函数内另一个对象的对象?

java - 比较器内部如何工作?

java - Bufferedreader 无法通过其他方法访问

java - Android 项目中带有 2 个字符串的 ListView/ListAdapter

java - 如何用java制作频率直方图

android - appcompat-v7 :27. 0.1 播放服务 map 问题

java - 如何使我的方法接受 x 个参数