1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| import org.apache.commons.beanutils.BeanUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.junit.Test; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class LuceneUtils { private static Directory directory; private static Analyzer analyzer; private static IndexWriter.MaxFieldLength maxFieldLength; private LuceneUtils() {} static{ try { directory = FSDirectory.open(new File(“E:/createIndexDB”)); analyzer = new StandardAnalyzer(Version.LUCENE_30); maxFieldLength = IndexWriter.MaxFieldLength.LIMITED; } catch (Exception e) { e.printStackTrace(); } } public static Directory getDirectory() { return directory; } public static Analyzer getAnalyzer() { return analyzer; } public static IndexWriter.MaxFieldLength getMaxFieldLength() { return maxFieldLength; }
public static Document javaBean2Document(Object object) { try { Document document = new Document(); Class<?> aClass = object.getClass(); Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); String method = “get” + name.substring(0, 1).toUpperCase() + name.substring(1); Method aClassMethod = aClass.getDeclaredMethod(method, null); String value = aClassMethod.invoke(object).toString(); System.out.println(value); document.add(new org.apache.lucene.document.Field(name, value, org.apache.lucene.document.Field.Store.YES, org.apache.lucene.document.Field.Index.ANALYZED)); } return document; } catch (Exception e) { e.printStackTrace(); } return null; }
public static Object Document2JavaBean(Document document, Class aClass) { try { Object obj = aClass.newInstance(); Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String value = document.get(name); BeanUtils.setProperty(obj, name, value); } return obj; } catch (Exception e) { e.printStackTrace(); } return null; } @Test public void test() { User user = new User(); LuceneUtils.javaBean2Document(user); } }
|