๋กœ์ผ“๐Ÿพ
article thumbnail
๋ฐ˜์‘ํ˜•

 

์ž๋ฐ”์—์„œ ๋ณ€์ˆ˜๋ช…์œผ๋กœ ํด๋ž˜์Šค๋ฅผ ์ธ์Šคํ„ด์Šคํ™” ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋ฐฉ๋ฒ• 1-์ธ์ˆ˜๋Š” ์—†๊ณ  ์ƒ์„ฑ์ž๋งŒ ์žˆ๋Š” ํด๋ž˜์Šค์—๋งŒ ํ•ด๋‹น

ํด๋ž˜์Šค์— ์ธ์ˆ˜๊ฐ€์—†๋Š” ์ƒ์„ฑ์ž๊ฐ€์žˆ๋Š” ๊ฒฝ์šฐ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Class๊ฐ์ฒด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ ์ด ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ธ์Šคํ„ด์Šค๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

Class<?> domainClass = Class.forName("com.femarket.domain." + domainName);
Object domain = domainClass.newInstance();

 

๋ฐฉ๋ฒ• 2

ํด๋ž˜์Šค์— ์ธ์ˆ˜๊ฐ€์—†๋Š” ์ƒ์„ฑ์ž๊ฐ€์—†๋Š” ๊ฒฝ์šฐ์—๋„ ์ž‘๋™ํ•˜๋Š” ๋” ์•ˆ์ „ํ•œ ๋ฐฉ๋ฒ•์€ ํด๋ž˜์Šค ๊ฐœ์ฒด๋ฅผ ์ฟผ๋ฆฌํ•˜์—ฌ ํ•ด๋‹น Constructor๊ฐœ์ฒด ๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ ์ด ๊ฐœ์ฒด์— ๋Œ€ํ•œ newInstance()๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

 

Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);

 

๊ทธ๋ฆฌ๊ณ  ์œ„ 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ Reflection์ด๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.


์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ๋˜ํ•œ ์ด๋Ÿฐ์‹์œผ๋กœ ๋ณ€์ˆ˜๋ช…์„ ์ด์šฉํ•˜์—ฌ ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ฝ”๋“œ ์‹คํ–‰์€ Node.js์—์„œ ์ง„ํ–‰ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

const service_01 = {
  log : () =>{
      return "service_01";
  }
}

module.exports = service_01;

 

const service_02 = {
    log : () =>{
        return "service_02";
    }
}

module.exports = service_02;

 

2๊ฐœ์˜ Service ๊ฐ์ฒด๋ฅผ ๋งŒ๋“  ํ›„ ์š”์ฒญํ•˜๋Š” url์— ๋”ฐ๋ผ์„œ ๊ฐ์ฒด๋ฅผ ๋‹ค๋ฅด๊ฒŒ ํ˜ธ์ถœํ•˜์—ฌ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์šฐ์„  ๊ฒฐ๊ณผ ํ™”๋ฉด์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

/service_01๋กœ ์š”์ฒญํ•ด service_01.js์˜ ๊ฐ์ฒด๋ฅผ ์ธ์Šคํ„ด์Šคํ™” ํ•˜์—ฌ service_01์˜ log ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

/service_02๋„ ๋งˆ์ฐฌ๊ฐ€์ง€์ž…๋‹ˆ๋‹ค.

 

์•„๋ž˜๋Š” ๋ผ์šฐํ„ฐ์—์„œ์˜ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

const express = require('express');
const router = express.Router();

const service_01 = require('../service/service_01');
const service_02 = require('../service/service_02');


const service = {
  service_01
  ,service_02
}

/* GET home page. */
router.get('/:service_name', function(req, res, next) {  
  const service_name = req.params.service_name;
  const obj = Reflect.get(service, `${service_name}`);

  res.render('index.pug' , {service_name: obj.log()});
});

module.exports = router;

const service ์•ˆ์— ๊ฐ๊ฐ์˜ service ๊ฐ์ฒด๋ฅผ ๋‹ด์Šต๋‹ˆ๋‹ค. ์ดํ›„ ๋“ค์–ด์˜ค๋Š” ์š”์ฒญ๊ฐ’(/:service_name)์— ๋”ฐ๋ผ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

Reflect.get ๋ฉ”์„œ๋“œ๋ฅผ ๋ณด๋ฉด service ๊ฐ์ฒด ์ค‘ ํ•ด๋‹นํ•˜๋Š” service_name์„ Reflection ํ•˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ดํ›„ res.render์—์„œ ๋ฟŒ๋ ค์ฃผ๋Š” ๊ฐ’์˜ value๋ฅผ obj.log๋ฅผ ํ•ด์คŒ์œผ๋กœ ๊ฐ๊ฐ€์˜ ๋‹ค๋ฅธ ๊ฐ์ฒด๋ฅผ ์ธ์Šคํ„ด์Šคํ™” ํ•˜๋Š” ๊ฑธ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด๋ฅผ ํ™œ์šฉํ•˜๋ฉด ์š”์ฒญ url์— ๋”ฐ๋ผ ๊ฐ๊ฐ์˜ ๋‹ค๋ฅธ ๊ฐ์ฒด๋ฅผ ์ธ์Šคํ„ด์Šคํ™” ํ•  ์ˆ˜ ์žˆ๋Š” ์ด์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

 

 

๋ฐ˜์‘ํ˜•
profile on loading

Loading...