Java 接口多实现动态调用

简单定义一个接口,做数据插入

public interface ImportingData<T> {
    AjaxResult addData(T t);
}

目前本文使用的是根据泛型类实现动态调用,在引入时必须明确是那个实体类,
还有种方法就是给每一个实现类定义业务类型的枚举,这时候子啊接口里面就得多写一个返回枚举的实现

 implements ImportingData<XXXX>

这里获取每一个实现以及对应的泛型类组成map,这样就能根据map特性动态调用

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class ApplicationContextFactory implements ApplicationContextAware {

    private final Map<Class<?>, ImportingData<Object>> importingDataService = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(ImportingData.class)
                .forEach((k, v) -> importingDataService.put(GenericTypeResolver.resolveTypeArgument(v.getClass(), ImportingData.class), v));
    }

    public <T> ImportingData<Object> getImportingDataService(Class<T> c) {
        return importingDataService.get(c);

    }


}

来个例子

定义一个实体类,实体类里面包含了两个泛型实现 implements ImportingData

@Data
public class Importing {

    @Valid
    private AAA aaa;
    @Valid
    private BBB bbb;
    
}
 public void addAll(Importing importing) {
 		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //拿到数据成员
        List<Method> methodList = Arrays.asList(importing.getClass().getDeclaredMethods());
        methodList.parallelStream().forEach(n -> {
        //根据反射拿到实体类的get对象
            if (n.getName().startsWith("get")) {
                Object invoke = null;
                try {
                    invoke = n.invoke(importing);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
                if (ObjectUtil.isNotNull(invoke)) {
                //调用
                    addDataAndLogAsync(n.getReturnType(), invoke, authentication);
                }
            }
        });
       
    }
    private Future<AjaxResult> addDataAndLogAsync(Class<?> returnType, Object invoke, Authentication authentication) {
    //因为是异步请求,可能涉及到用户获取之类的所以手动传播上下文,没有的可以不用
        return executorService.submit(() -> {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            AjaxResult ajaxResult = null;
            //这里可以定义日志啥的
            try {
            //这里getImportingDataService可能为空,可以加一层判断
                ajaxResult = applicationContextFactory.getImportingDataService(returnType).addData(invoke);            
            } catch (Exception e) {
                log.error("数据异常:", e);
            }
            return ajaxResult;
        });
    }
    ```

这样的话实体类不管加多少只要是实现了都可以动态调用
Java中的多线程允许程序在同一时间内执行多个任务。在接口调用上下文中,这通常意味着在并发环境中通过接口实现共享资源或服务。 ### Java多线程实现接口调用的步骤: 1. **创建接口**:首先,需要创建一个接口,其中包含所有预期由实现接口提供操作的方法签名(即方法名、返回型和参数列表)。在这个接口中,你可以声明同步方法,用于确保对共享资源的操作不会发生冲突。 ```java public interface MyInterface { void performAction(); } ``` 2. **实现接口**:然后,创建多个实现这个接口,并为每个提供其特有的实现。这些将通过实现接口提供的方法来访问和更新共享资源。 ```java public class ImplementationA implements MyInterface { @Override public void performAction() { // 实现逻辑 } } public class ImplementationB implements MyInterface { @Override public void performAction() { // 实现逻辑 } } ``` 3. **创建线程**:接着,使用`Thread`或`Runnable`接口来创建新线程,这些线程将在运行时实例化上述实现的对象并调用`performAction()`方法。 ```java public class ThreadCreator { public static void main(String[] args) { MyInterface objA = new ImplementationA(); MyInterface objB = new ImplementationB(); Thread threadA = new Thread(objA); Thread threadB = new Thread(objB); threadA.start(); threadB.start(); } } ``` 4. **同步控制**:如果接口中的某些方法需要对共享资源进行操作,可以使用`synchronized`关键字标记这些方法来确保线程安全。这意味着只有一个线程可以在给定时间点执行这些方法,从而避免了数据竞争和错误的结果。 ```java public interface SafeMyInterface { synchronized void performSafeAction(); } public class SafeImplementation implements SafeMyInterface { private int sharedResource; @Override public synchronized void performSafeAction() { // 管理共享资源的逻辑 } } ``` ### 相关问题: 1. 在Java中如何确保多线程环境下的代码安全性和一致性? 2. 使用Java多线程时,什么是死锁以及如何预防它? 3. 怎样在Java中利用接口实现线程间的协作与通信?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值