Skip to content

Instantly share code, notes, and snippets.

@idiottiger
Created August 25, 2015 13:43
Show Gist options
  • Save idiottiger/ee3e542b2ec3294ddd69 to your computer and use it in GitHub Desktop.
Save idiottiger/ee3e542b2ec3294ddd69 to your computer and use it in GitHub Desktop.
add @JavascriptInterface annotation
import re
import codecs
import tempfile
METHOD_PATTERN = re.compile('\s*[^/]+\s*(public|private|protected)\s+[^class]\s*[a-zA-Z][a-zA-Z0-9_]*\s+[a-zA-Z][a-zA-Z0-9_]*\s*\(')
JS_METHOD_PATTERN = re.compile('\s*[^/]+\s*public\s+[^class]\s*[a-zA-Z][a-zA-Z0-9_]*\s+[a-zA-Z][a-zA-Z0-9_]*\s*\(')
JS_INTERFACE_PATTERN = re.compile('\s*@JavascriptInterface')
JS_ANNOTATION = '\t@JavascriptInterface\n'
JS_ANNOTATION_CLASS_NAME = 'android.webkit.JavascriptInterface'
JS_ANNOTATION_IMP = 'import android.webkit.JavascriptInterface;\n'
CLASS_PATTERN = re.compile('\s*public\s+(final\s+)?class\s+[a-zA-Z][a-zA-Z0-9_]*')
IMP_PATTERN = re.compile('\s*import\s+[a-zA-Z][a-zA-Z0-9_]*')
def process_java_file(fileName):
list_lines = []
with codecs.open(fileName, "r", "utf-8") as jfile:
skip_method = False
last_import_index = 0
index = 0
found_annotation_imp = False
for line in jfile:
if IMP_PATTERN.match(line):
last_import_index = index
if line.find(JS_ANNOTATION_CLASS_NAME) != -1:
found_annotation_imp = True
elif not found_annotation_imp and CLASS_PATTERN.match(line):
found_annotation_imp = True
list_lines.insert(last_import_index + 1, JS_ANNOTATION_IMP)
elif JS_INTERFACE_PATTERN.match(line): #already has the interface annotation, will skill this method
skip_method = True
elif skip_method and METHOD_PATTERN.match(line):
print ">>> skip method:" + line
skip_method = False
elif JS_METHOD_PATTERN.match(line):
list_lines.append(JS_ANNOTATION)
print line
list_lines.append(line)
index = index + 1
jfile.close()
out = codecs.open(fileName, 'w+', 'utf-8')
for write_line in list_lines:
out.write(write_line)
out.close()
def process_list_file(fileListFile):
with open(fileListFile) as fileNameLines:
for fileName in fileNameLines:
if fileName.find('#') == -1 and len(fileName.strip()) != 0:
print 'fileName :' + fileName
process_java_file(fileName.strip())
process_list_file(r"D:\dev\project\js\list.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment