import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
/**
* @author ChenZhenJian
* @date 2015年11月19日
* @modify 2016 -1 -7
*
*/
@Service( "callTimerImpl")
public class CallTimerImpl implements ICallTimer {
//
private List<Map<String, Object>> beans = new LinkedList<Map<String, Object>>();
public CallTimerImpl() throws Exception {
this.init();
}
/**
*
*
* @throws Exception
*/
@SuppressWarnings("rawtypes")
private void init() throws Exception {
try {
@SuppressWarnings( "resource")
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationConsumer.xml" });
context.start();
// 从配置文件读取 Map格式如<attent,timerControlAttentImpl>
Properties prop = new Properties();
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream( "timerPower.properties");
prop.load(inputStream);
Iterator<Entry<Object, Object>> it = prop.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it. next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
// 根据配置文件的参数,去 contex中获取bean 并且添加到List中
Object bean = context.getBean(value);
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put(key, bean);
if ( null != hashMap) {
beans.add(hashMap);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
}
/**
*
*
* @throws Exception
* @throws NoSuchMethodException
*/
public List<String[]> findTimer() throws NoSuchMethodException, Exception {
List<String[]> objectList = new LinkedList<String[]>();
try {
for (Map<String, Object> map : beans) {
for (String key : map.keySet()) {
Object obj = map.get(key);
Class<? extends Object> class1 = obj.getClass();
Method method = class1.getMethod("preInit" );
String[] list1 = (String[]) method.invoke(obj);
if ( null != list1) {
objectList.add(list1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
}
return objectList;
}
/**
*
*
* @param name
*
* @param state
*
* @throws Exception
*/
public String callTimer(String name, int state) throws Exception {
try {
for (Map<String, Object> map : beans) {
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
String next = iterator. next();
if (next.equals(name)) {
Object object = map.get(next);
Class<? extends Object> class1 = object.getClass();
Method method = class1.getMethod("runTimer" , String.class, int.class);
String invoke = (String) method.invoke(object, name, state);
return invoke;
}
}
return "" ;
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
}
}
java 读取properties + 类反射的应用
最新推荐文章于 2022-09-23 17:22:20 发布