Use reflection to load classes from configuration files and resolve specific dependencies based on configuration files.

Config file reflect.properties:

1AdminDao=reflect.AdminDao
1GuestDao=reflect.GuestDao
1Manager=reflect.Manager
2Manager:AdminDao
2Manager:GuestDao
Copy the code

Corresponding class file AdminDao:

package reflect;

public class AdminDao {
	public AdminDao(a){
		System.out.println("Successfully instantiated AdminDao"); }}Copy the code

Corresponding class file GuestDao:

package reflect;

public class GuestDao {
	public GuestDao(a){
		System.out.println("Successfully instantiated the GuestDao"); }}Copy the code

Corresponding class file Manager:

package reflect;

public class Manager {
	private AdminDao adminDao = null;
	private GuestDao guestDao = null;
	public Manager(a) {
		System.out.println("Manage successfully instantiated");
	}
	public void setAdminDao (Object o) {
		this.adminDao = (AdminDao)o;
		System.out.println("Resolve adminDao dependencies");
	}
	public void setGuestDao (Object o) {
		this.guestDao = (GuestDao)o;
		System.out.println("Resolve guestDao dependencies"); }}Copy the code

Reflection Test Factory class:

package reflect;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ObjectFactory {
	public static Map<String,Object> map = new HashMap<String,Object>();
	
	static {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("src/reflect.properties"));
			String str = br.readLine();
			while(str ! =null) {
				char c = str.charAt(0);
				switch (c) {
					case '1':
						String[] arr = str.substring(1).split("=");
						Object o = Class.forName(arr[1]).newInstance();
						map.put(arr[0].trim().toLowerCase(), o);
						break;
					case '2':
						String[] arr2 = str.substring(1).split(":");
						Object obj = map.get(arr2[0].trim().toLowerCase());
						Object fieldObj = map.get(arr2[1].trim().toLowerCase());
						String methodName = "set"+arr2[1].substring(0.1).toUpperCase()+arr2[1].substring(1);
						Method method = obj.getClass().getDeclaredMethod(methodName, Object.class);
						method.invoke(obj, fieldObj);
						break; } str = br.readLine(); }}catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch(IOException e) { e.printStackTrace(); }}}public static void main(String[] args) {
		Set<String> set = map.keySet();
		for (String string:set) {
			System.out.println(string+"--"+map.get(string)); }}}Copy the code

Running results:

Successfully instantiated AdminDao Successfully instantiated GuestDao Manage Successfully instantiated Resolve AdminDao dependencies Resolve GuestDao dependencies admindao--reflect.AdminDao@10d1f30 manager--reflect.Manager@7aacc1 guestdao--reflect.GuestDao@1e3cabdCopy the code