Вы можете создать два класса DTO, преобразовать вашу сущность в соответствующий класс DTO и вернуть его.
public class MyEntity {
private String name;
private int age;
private int weight;
public PersonDetailedDTO toPersonDetailedDTO() {
PersonDetailedDTO person = PersonDetailedDTO();
//...
return person;
}
public PersonDTO toPersonDTO() {
PersonDTO person = PersonDTO();
//...
return person;
}
}
public class PersonDetailedDTO {
private String name;
private int age;
private int weight;
}
public class PersonDTO {
private String name;
private int age;
}
@GetMapping
public PersonDTO get() {
//...
return personService.getPerson().toPersonDTO();
}
@GetMapping("/my_url")
public PersonDetailedDTO get() {
//...
return personService.getPerson().toPersonDetailedDTO();
}
The function handle operator in MATLAB acts essentially like a pointer to a specific instance of a function. Some of the other answers have discussed a few of its uses, but I'll add another use here that I often have for it: maintaining access to functions that are no longer "in scope".
For example, the following function initializes a value count
, and then returns a function handle to a nested function increment
:
function fHandle = start_counting(count)
disp(count);
fHandle = @increment;
function increment
count = count+1;
disp(count);
end
end
Since the function increment
is a nested function, it can only be used within the function start_counting
(i.e. the workspace of start_counting
is its "scope"). However, by returning a handle to the function increment
, I can still use it outside of start_counting
, and it still retains access to the variables in the workspace of start_counting
! That allows me to do this:
>> fh = start_counting(3); % Initialize count to 3 and return handle
3
>> fh(); % Invoke increment function using its handle
4
>> fh();
5
Notice how we can keep incrementing count even though we are outside of the function start_counting
. But you can do something even more interesting by calling start_counting
again with a different number and storing the function handle in another variable:
>> fh2 = start_counting(-4);
-4
>> fh2();
-3
>> fh2();
-2
>> fh(); % Invoke the first handle to increment
6
>> fh2(); % Invoke the second handle to increment
-1
Notice that these two different counters operate independently. The function handles fh
and fh2
point to different instances of the function increment
with different workspaces containing unique values for count
.
In addition to the above, using function handles in conjunction with nested functions can also help streamline GUI design, as I illustrate in this other SO post.
Функциональные маркеры являются чрезвычайно мощным инструментом в Matlab. Хорошее начало - прочитать онлайн-справку, которая даст вам гораздо больше, чем я могу. В командной строке введите
doc function_handle
Дескриптор функции - это простой способ создать функцию в одну строку. Например, предположим, что я хотел бы численно интегрировать функцию sin (k * x), где k имеет некоторое фиксированное внешнее значение. Я мог бы использовать встроенную функцию, но дескриптор функции намного аккуратнее. Определите функцию
k = 2;
fofx = @(x) sin(x*k);
. Теперь я могу оценить функцию fofx в командной строке. MATLAB знает, что такое k, поэтому мы можем теперь использовать fofx как функцию.
fofx(0.3)
ans =
0.564642473395035
Фактически, мы можем передавать fofx вокруг, эффективно как переменную. Например, давайте вызовем quad для численного интегрирования. Я выберу интервал [0, pi / 2].
quad(fofx,0,pi/2)
ans =
0.999999998199215
Как вы можете видеть, quad выполнил численное интегрирование. (Кстати, встроенная функция была бы, по крайней мере, на порядок медленнее, и с ней гораздо проще работать.)
x = linspace(0,pi,1000);
tic,y = fofx(x);toc
Elapsed time is 0.000493 seconds.
Для сравнения попробуйте встроенную функцию.
finline = inline('sin(x*k)','x','k');
tic,y = finline(x,2);toc
Elapsed time is 0.002546 seconds.
Отличная вещь в дескрипторе функции - вы можете определить это на лету. Минимизируйте функцию cos (x) за интервал [0,2 * pi]?
xmin = fminbnd(@(x) cos(x),0,2*pi)
xmin =
3.14159265358979
Существует множество способов использования дескрипторов функций в MATLAB. Я только поцарапал поверхность здесь.
Отказ от ответственности: код не проверен ...
Оператор дескриптора функции позволяет создавать ссылку на функцию и передавать ее, как и любую другую переменную:
% function to add two numbers
function total = add(first, second)
total = first + second;
end
% this variable now points to the add function
operation = @add;
Как только вы ' У нас есть дескриптор функции, вы можете вызывать его так же, как обычную функцию:
operation(10, 20); % returns 30
Одна приятная вещь в дескрипторах функций заключается в том, что вы можете передавать их, как и любые другие данные, так что вы можете писать функции, которые действуют на другие функции. Это часто позволяет вам легко отделить бизнес-логику:
% prints hello
function sayHello
disp('hello world!');
end
% does something five times
function doFiveTimes(thingToDo)
for idx = 1 : 5
thingToDo();
end
end
% now I can say hello five times easily:
doFiveTimes(@sayHello);
% if there's something else I want to do five times, I don't have to write
% the five times logic again, only the operation itself:
function sayCheese
disp('Cheese');
end
doFiveTimes(@sayCheese);
% I don't even need to explicitly declare a function - this is an
% anonymous function:
doFiveTimes(@() disp('do something else'));
Документация Matlab содержит более полное описание синтаксиса Matlab и описывает некоторые другие применения дескрипторов функций, таких как графические обратные вызовы.