How to solve missing javah in Java 10 – ugly way

In Java 10, there is no longer javah tool. It means, that you can’t extract information regarding native interfaces easily. It’s not that simple to generate header files based on compiled – class – files.

If you desperately need to process lots of class files, you can alway hack through using javap tool. You can create “reduced” source files that will be more than enough for javac to generate headers. It’s not ideal, but in case of “it should be on my desk in 10 minutes” like tasks, it can be your day saver.

Have fun!

#!/bin/bash

# FIRST_ARG - full class name (with package)
# Note! I have a strong assumption that:
#  - native method is declared inside class that is part of package
#  - native method is not declared inside class that is inner class
# SECOND_ARG - class path

CLASS_NAME=`javap -cp $2 $1 | \
  grep -v "Compiled from" | \
  grep "public class" | \
  cut -f3 -d" " | \
  awk -F"." '{ print $NF }'`

PACKAGE_NAME=`javap -cp $2 $1 |i \
  grep -v "Compiled from" | \
  grep "public class" | \
  cut -f3 -d" " | \
  sed s/\.${CLASS_NAME}$//`

DIR_NAME=`echo $PACKAGE_NAME | sed 's|\.|/|g'`
mkdir -p java_jni/${DIR_NAME}

JAVA_FILE="java_jni/${DIR_NAME}/${CLASS_NAME}.java"

# There are lots of strong assumptions here !!
echo "package ${PACKAGE_NAME};" > ${JAVA_FILE}
echo "public class ${CLASS_NAME} {" >> ${JAVA_FILE}
javap -cp $2 $1 | grep "native" >> ${JAVA_FILE}
echo "}" >> ${JAVA_FILE}

# Now, we can generate header
mkdir -p c_header
javac -h c_header ${JAVA_FILE}

If you are looking for more JNI samples, take a look here: http://jnicookbook.owsiak.org

Leave a comment

Your comment