Skip to content

Commit

Permalink
fix method call logic, add nonOwner example
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Oct 2, 2021
1 parent 5bc6ee5 commit 5d16951
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
39 changes: 34 additions & 5 deletions src/main/scala/ScalaBasic/DynamicProxy1/MatchService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,68 @@ import java.lang.reflect.Proxy

class MatchService {

/** DEMO 1 : Ourselves */
// create a person
val tom = getPersonInfo("tom", "male", "cook")

// get our own proxy (represents the tom instance)
// we will call the methods via this proxy (OwnerProxy)
val OwnerProxy = getOwnerProxy(tom)

println("Name = " + OwnerProxy.getName()) // tom
println("Interests = " + OwnerProxy.getInterests()) // cook

println("Gender = " + OwnerProxy.getGender())
//println("Gender = " + OwnerProxy.getGender())

OwnerProxy.setInterests("hiking")
println("Interests = " + OwnerProxy.getInterests()) // hiking
println("** Interests = " + OwnerProxy.getInterests()) // hiking

OwnerProxy.setScore(100)
println("Score = " + OwnerProxy.getScore()) // still 0

// method
println("=============================")

/** DEMO 2 : Other users */
val Ann = getPersonInfo("Ann", "female", "drink")
val nonOwnerProxy = getNonOwnerProxy(Ann)

println("Name = " + nonOwnerProxy.getName()) // Ann
println("Interests = " + nonOwnerProxy.getInterests()) // drink
println("Score = " + nonOwnerProxy.getScore())

//println("Gender = " + OwnerProxy.getGender())

OwnerProxy.setInterests("eat")
println("** Interests = " + nonOwnerProxy.getInterests()) // eat

nonOwnerProxy.setScore(100)
println("Score = " + nonOwnerProxy.getScore()) // still 100


// method
def getPersonInfo(name:String, gender:String, interests:String):PersonBean = {
val person = new PersonBeanImplement()
person.setName(name)
person.setGender(gender)
person.setInterests(interests)

person
}

def getOwnerProxy(person: PersonBean):PersonBean = {
Proxy.newProxyInstance(
person.getClass().getClassLoader,
person.getClass().getClassLoader(),
person.getClass().getInterfaces(),
new OwnerInvocationHandler(person)
).asInstanceOf[PersonBean]
}

def getNonOwnerProxy(person: PersonBean):PersonBean = {
Proxy.newProxyInstance(
person.getClass().getClassLoader(),
person.getClass().getInterfaces(),
new NonOwnerInvocationHandler(person)
).asInstanceOf[PersonBean]
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class OwnerInvocationHandler extends InvocationHandler{
return new IllegalAccessException()

// if `set` method, then we invoke directly
} else if (method.getName().equals("set")){
} else if (method.getName().startsWith("set")){
return method.invoke(person, args(0).toString)
}
null
Expand Down

0 comments on commit 5d16951

Please sign in to comment.