Java实现访问控制矩阵代码
时间: 2024-05-01 07:17:24 浏览: 83
Java访问权限控制源代码
对于Java实现访问控制矩阵代码的问题,我可以提供一些参考代码:
```java
public class AccessControlMatrix {
private final Set<String> subjects;
private final Set<String> objects;
private final Map<String, Map<String, Set<String>>> permissions;
public AccessControlMatrix(Set<String> subjects, Set<String> objects) {
this.subjects = subjects;
this.objects = objects;
permissions = new HashMap<>();
for (String subject : subjects) {
permissions.put(subject, new HashMap<>());
for (String object : objects) {
permissions.get(subject).put(object, new HashSet<>());
}
}
}
public void addPermission(String subject, String object, String permission) {
if (!subjects.contains(subject)) {
throw new IllegalArgumentException("Subject not in the matrix.");
}
if (!objects.contains(object)) {
throw new IllegalArgumentException("Object not in the matrix.");
}
permissions.get(subject).get(object).add(permission);
}
public boolean hasPermission(String subject, String object, String permission) {
if (!subjects.contains(subject) || !objects.contains(object)) {
return false;
}
return permissions.get(subject).get(object).contains(permission);
}
}
```
这是一个基本的访问控制矩阵实现,支持添加权限和查询是否有权限。在实际使用中,需要根据具体的应用场景进行适当的修改和优化。
阅读全文