Skip to content

Commit

Permalink
[bugfix] Fixing a ClassNotFoundException
Browse files Browse the repository at this point in the history
Resolves #30.

This fixes a problem where a var that looked like a Java class
constructor would cause Yagni to try to resolve the class it thought
existed. Unfortunately, while `resolve` returns nil when it believes
it's dealing with a Clojure symbol, when it's targeting something it
believes to be a Java class it throws a ClassNotFoundException.

This commit wraps the resolve attempt in a try/catch block - it's ugly,
but I'm not aware of a more elegant solution at the moment.
  • Loading branch information
venantius committed Jul 17, 2015
1 parent 2735cc8 commit a4297f3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/yagni/jvm.clj
@@ -1,6 +1,7 @@
(ns yagni.jvm
"Utility functions for working with the JVM."
(:require [clojure.string :as string]))
(:require [clojure.reflect :refer [resolve-class]]
[clojure.string :as string]))

(defn class-name->var-name
"Return the var name for the given class name.
Expand Down Expand Up @@ -29,6 +30,13 @@
c (last v)]
(symbol (string/join "." [n c]))))

(defn can-resolve-class?
[c]
(try
(resolve c)
(catch ClassNotFoundException e
false)))

(defn is-class-generator?
"Check to see if a given var is a class generator. If it is, returns the
Java class for the generator in question.
Expand All @@ -42,10 +50,10 @@
(or
(and
(.startsWith name "->")
(resolve (var-name->class-name (symbol n (subs name 2)))))
(can-resolve-class? (var-name->class-name (symbol n (subs name 2)))))
(and
(.startsWith name "map->")
(resolve (var-name->class-name (symbol n (subs name 5))))))))
(can-resolve-class? (var-name->class-name (symbol n (subs name 5))))))))

(defn is-class-constructor?
"Check to see if a given symbol is a class constructor (e.g. `(String.)`)"
Expand Down
6 changes: 6 additions & 0 deletions test/yagni/jvm_test.clj
Expand Up @@ -14,6 +14,10 @@
(defprotocol SampleInterface
(foo [this]))

(defn ->non-class-converter
[]
true)

(deftest class-name->var-name
(is (= (jvm/class-name->var-name yagni.jvm_test.SampleInterface)
'yagni.jvm-test/SampleInterface)))
Expand All @@ -26,6 +30,8 @@
(deftest is-class-generator?-works
(is (some? (jvm/is-class-generator? 'yagni.jvm-test/->FooType)))
(is (some? (jvm/is-class-generator? 'yagni.jvm-test/->FooRecord)))
(is (false? (jvm/is-class-generator? 'yagni.jvm-test/->non-class-converter)))
(is (some? (jvm/is-class-generator? 'yagni.jvm-test/->non-class-converter)))
(is (some? (jvm/is-class-generator? 'yagni.jvm-test/map->FooRecord))))

(deftest find-generator-fns-works
Expand Down

0 comments on commit a4297f3

Please sign in to comment.