Java-模块化讲解练习代码

myOne模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
f1包:
package com.f1;

public class Student {
public void study(){
System.out.println("好好学习,天天向上");
}
}

f2包:
package com.f2;

public class Teacher {
public void teach(){
System.out.println("化作春泥更护花");
}
}

f3包:
package com.f3;

public interface MyService {
void service();
}

impl包:
package com.f3.impl;

import com.f3.MyService;

public class Czxy implements MyService {
@Override
public void service() {
System.out.println("传智学院");
}
}

package com.f3.impl;

import com.f3.MyService;

public class Itheima implements MyService {
@Override
public void service() {
System.out.println("it黑马");
}
}

src包下:module-info.java:

import com.f3.MyService;
import com.f3.impl.Czxy;
import com.f3.impl.Itheima;

module myOne {
exports com.f1;
exports com.f3;

// provides MyService with Itheima;
provides MyService with Czxy;
}

myTwo模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
cn.t1包下:
Test01:

package cn.t1;

import com.f1.Student;
//import com.f2.Teacher;

public class Test01 {
public static void main(String[] args) {
Student s = new Student();
s.study();

//Teacher t = new Teacher();
}
}



Test02:

package cn.t1;

import com.f3.MyService;
import java.util.ServiceLoader;

public class Test02 {
public static void main(String[] args) {
//加载服务
ServiceLoader<MyService> myServices = ServiceLoader.load(MyService.class);

//遍历服务
for(MyService my : myServices){
my.service();
}
}
}

src包下:module-info.java:
import com.f3.MyService;

module myTwo {
requires myOne;

uses MyService;
}