2 Lucene筆記(二):建立LuceneUtils工具
阿新 • • 發佈:2019-01-01
publicclass LuceneUtils {
public LuceneUtils() {}
private static Directory directory;
private static Version version;
private static Analyzer analyzer;
private static MaxFieldLength maxFieldLength;
static{
try {
directory = FSDirectory. open(new File("F:/LuceneDB")) ;
version = Version. LUCENE_30;
analyzer = new StandardAnalyzer( version);
maxFieldLength = MaxFieldLength.LIMITED;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException( e);
}
}
public static Directory getDirectory() {
return directory;
}
public static void setDirectory(Directory directory) {
LuceneUtils. directory = directory;
}
public static Version getVersion() {
return version;
}
public static void setVersion(Version version) {
LuceneUtils. version = version;
}
public static Analyzer getAnalyzer() {
return analyzer;
}
public static void setAnalyzer(Analyzer analyzer) {
LuceneUtils. analyzer = analyzer;
}
public static MaxFieldLength getMaxFieldLength() {
return maxFieldLength;
}
public static void setMaxFieldLength(MaxFieldLength maxFieldLength) {
LuceneUtils. maxFieldLength = maxFieldLength ;
}
/**
*javabean-->doc
*/
public static Document javaBeanToDocument(Object obj) throws Exception {
Document doc = new Document();
Class clazz = obj.getClass();
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
for(java.lang.reflect.Field field : fields ){
field.setAccessible( true); //暴力反射
String name = field.getName();
String methodName = "get"+ name.substring(0, 1).toUpperCase()+name.substring(1,name .length());
Method method = clazz.getMethod(methodName , null);
String value = method.invoke(obj, null).toString();
//System.out.println(name+"="+value);
doc.add( new Field( name, value, Store. YES, Index.ANALYZED));
}
return doc;
}
/**
* doc-->javabean
* /
public static Object documentToJavaBean(Document doc, Class clazz) throws Exception{
Object obj = clazz.newInstance();
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
for(java.lang.reflect.Field field : fields ){
field.setAccessible( true); //暴力反射
String name = field.getName();
String value = doc.get( name);
BeanUtils. setProperty(obj, name, value);
}
return obj;
}
//測試
public static void main(String[] args) throws Exception {
Article article = new Article(1, "搜尋標題", "通過關鍵字搜尋文章,搜點什麼好呢?" );
Document document = LuceneUtils.javaBeanToDocument(article);
/*System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));*/
System. out.println( "----------------------------------" );
Article article1 = (Article) LuceneUtils.documentToJavaBean(document,Article.class);
System. out.println( article1);
}
}