简体   繁体   中英

Grails: Integrating a Java Class

I created a new Grails 3 application in IntelliJ IDE.

Here is the folder structure view from IntelliJ

文件夹布局在同一级别上显示grails-app /和src /

I then created two files, a controller with the following code,

package grailsjavatest
import test.JavaTest;
class JavaTestController {

    def index() {
        JavaTest jt = new JavaTest();
        render jt.someAction();
    }
}

and a Java files with the following code (in src/java/test/JavaTest.java),

package test;

class JavaTest{

    public String someAction()
    {
        return "<html> <body> <b> Hello From Java! </b> </body> </html>";
    }

}

However the following project errors with the following error,

[the java process command was removed as it is a bit long.]

| Running application...
startup failed:

/Users/user/IdeaProjects/GrailsJavaTest/grails-app/controllers/grailsjavatest/JavaTestController.groovy: 2: unable to resolve class test.JavaTest
 @ line 2, column 1.
   import test.JavaTest;
   ^

1 error



FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileGroovy'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
| Error Failed to start server (Use --stacktrace to see the full trace)

Process finished with exit code 1

If I change the controller code to,

package grailsjavatest
class JavaTestController {

    def index() {
        render "<html> <body> <b> Hello From Java! </b> </body> </html>";
    }
}

the page renders as expect (but obviously not calling the java code).

Edit

Here is the file structure with the package created,

JavaTest作为软件包而不是普通文件夹

Your JavaTest class is declared with default (package-private) modifier, so it is only visible to other classes declared in the same 'test' package. Add the 'public' keyword to the start of the class definition (ie 'public class JavaTest{ yada, yada').

Alternatively follow the instructions given by Grails and "Run with --stacktrace option to get the stack trace." which should show you what's wrong.

My previous answer made little sense.

The problem is that 'test' is not a package folder (which contain a dot in IntelliJ), but a plain folder. But in order to add a package folder to your Java folder, your Java folder needs to be marked as a 'source folder' (which have a blue color). Right-click on the java folder, select 'Mark directory as' - 'Sources root'. The 'test' folder will now automatically be marked as a package folder (at least in IntelliJ 2016.1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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