From a4297f3c58c77ab7109c77831ca81bbfe30f168d Mon Sep 17 00:00:00 2001 From: Ursa Americanus Kermodei Date: Thu, 16 Jul 2015 23:16:48 -0700 Subject: [PATCH] [bugfix] Fixing a ClassNotFoundException 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. --- src/yagni/jvm.clj | 14 +++++++++++--- test/yagni/jvm_test.clj | 6 ++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/yagni/jvm.clj b/src/yagni/jvm.clj index 442720e..269494e 100644 --- a/src/yagni/jvm.clj +++ b/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. @@ -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. @@ -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.)`)" diff --git a/test/yagni/jvm_test.clj b/test/yagni/jvm_test.clj index 7bef181..29c85e9 100644 --- a/test/yagni/jvm_test.clj +++ b/test/yagni/jvm_test.clj @@ -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))) @@ -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