5

My IDE is really good about finding the corresponding Java source code for JDK classes. For example, I can open java.lang.String in my IDE and see the actual Java source code. However, when I try to open sun.net.www.http.HttpClient (which is included in the Java SDK), my IDE just shows me the decompiled .class file, which is difficult to read.

My IDE on macOS is looking for the source code in /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/src.zip, and if I unzip that archive I can find String.java, but HttpClient.java is nowhere to be found. So it makes sense that my IDE can't find it.

Where can I get the complete JDK source code?

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • If you use Intellij, and your project is using maven (or similar) for dependencies, it can automatically download sources, just as it can download the api-docs, where available. – emanciperingsivraren Feb 17 '17 at 21:47
  • 1
    @emanciperingsivraren I regularly do this for Java libraries, but IntelliJ has special handling for the JDK itself, and the Oracle JDK provides only some of the JDK source code. – Cory Klein Feb 17 '17 at 21:49

1 Answers1

7

If you're on Linux, you may be able to find a more complete source code archive at the OpenJDK Project. However on macOS and possibly other platforms, here is a method that worked for me:

Download the complete Java source code from Github

git clone https://github.com/openjdk-mirror/jdk.git
cd jdk
git checkout jdk8u/jdk8u/master    # For Java 8

Find the Java package you're interested in

find . -name HttpClient.java       # Or whatever class you want
./src/share/classes/sun/net/www/http/HttpClient.java

Here you can see that sun.net.www.http.HttpClient is in the sun package, which is located in the src/share/classes directory.

Make a new source archive with the package in it

mkdir ~/java
# Replace path below with location of JDK on your machine
unzip /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/src.zip -d ~/java
cp -r ./src/share/classes/sun ~/java

Rebuild the archive and put it back

cd ~/java
zip -r src.zip *
cp src.zip /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/src.zip

You may have to restart your IDE, but now it should be able to find the previously missing source code.

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • 2
    A better way to get the source code goes here [link](https://stackoverflow.com/questions/2896727/where-to-find-java-jdk-source-code) sudo apt-get install openjdk-7-source – lin Nov 14 '17 at 01:55
  • 1
    @ChaojunZhong That only installs src.zip which is what he already has. – Thorbjørn Ravn Andersen Dec 25 '18 at 23:17