JGit has a SubmoduleStatusCommand
that lists all known submodules. Note that this command works only on non-bare repositories.
Git git = Git.open( new File( "/path/to/repo/.git" ) );
Map<String,SubmoduleStatus> submodules = git.submoduleStatus().call();
SubmoduleStatus status = submodules.get( "repository/core" );
ObjectId headId = status.getHeadId();
As you can see, the command returns a map of submodules-names along with their respective SubmoduleStatus
which includes the SHA-1 of the HEAD commit.
There is also an article about JGit's submodule API that I wrote some time ago that has some more details.
For a bare repository you would have to read the the submodule's HEAD ID directly from the repository's object database like so:
try( RevWalk revWalk = new RevWalk( repository ) ) {
RevCommit headCommit = revWalk.parseCommit( repository.resolve( Constants.HEAD ) );
}
try( TreeWalk treeWalk = TreeWalk.forPath( repository, "repository/core", headCommit.getTree() ) ) {
ObjectId blobId = treeWalk.getObjectId( 0 );
ObjectLoader objectLoader = repository.open( blobId, Constants.OBJ_BLOB );
try( InputStream inputStream = objectLoader.openStream() ) {
// read contents from the input stream
}
}