Run single java file with standard main(String [] args) method - Android Studio

后端 未结 5 1000
青春惊慌失措
青春惊慌失措 2020-12-17 16:16

To start with - Yes, I know that this is crazy/strange. But I need it :).

I want to find simpliest way to run single java file (and prefer non-termi

相关标签:
5条回答
  • 2020-12-17 16:37

    If nothing else, you can make a quick JUnit test that calls your class's main method.

    0 讨论(0)
  • 2020-12-17 16:42

    The easiest way (for me) is to do a right click in your editor and select "Run ClassName.main()". See screenshot. Using Android Studio version 1.4.1.

    0 讨论(0)
  • 2020-12-17 16:54

    This may be too late but this might help other developers,

    If you're using JAVA, you need to write it as told by @Andrey.

    If you're using Kotlin, you can simply write a function without making a Class.

    fun main(){
         println("you")
    }
    

    This will work.

    But, remember, function name should only be main and don't use anything that is part of Android JDK inside this main function.

    Ex:- if you write

    fun main(){
       Log.e("you","you")
    }
    

    Now as Log is part of Android, you'll get runtime exception saying

    Exception in thread "main" java.lang.RuntimeException: Stub!
    
    0 讨论(0)
  • 2020-12-17 16:56

    1) Create the class with main() method:

    public class Test1 {
    
        public static void main(String[] args) {
            System.out.println("hello1");
        }
    }
    

    2) hit ctrl+shift+F10 (or ctrl+shift+R for Mac)

    It will compile, assemble and print

    hello1

    0 讨论(0)
  • 2020-12-17 16:57

    One thing that might be confusing you, like it was confusing me:

    If there is the standard method to start Java application

    public static void main (String[] args ) {
    // your block here
    
    }
    

    Android Studio will automatically give an option "Run YourClass.mainActivity()", when you right-click anywhere in the editor's editing space.

    Just right click in the Java file and there will be an option to run that particular Java class.

    0 讨论(0)
提交回复
热议问题