forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCar.java
More file actions
32 lines (22 loc) · 866 Bytes
/
Copy pathCar.java
File metadata and controls
32 lines (22 loc) · 866 Bytes
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
package modern.challenge;
import java.lang.reflect.Field;
public class Car {
private String type = "Dacia";
public class Engine {
private String power = "80 hp";
public void addEngine() {
System.out.println("Add engine of " + power + " to car of type " + type);
}
}
public static Car newCar(String type, String power)
throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Car newCar = new Car();
newCar.type = type;
Engine engine = newCar.new Engine();
// engine.power = power; // this will work
Field powerField = Engine.class.getDeclaredField("power");
// powerField.setAccessible(true); // this is needed before JDK 11
powerField.set(engine, power);
return newCar;
}
}